Difference between eventListener and event.target on this question

41 views Asked by At

Im trying to solve a simple problem in Js, where i need to rotate a string in js(only) on my html, but im facing problems with this two event handlers(im calling eventListener and event.target of event handlers because im not sure if they do the same thing or similar...).

Here is the html code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="Training">
        <meta name="author" content="Vitor Mota">
        <title>Training</title><!--Practice-->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">                      
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="cssFile.css">
        <script src="JsExc.js" defer></script>
    </head>
    <body >

       
       <div class="Test_space" id="target">
        <button id="btnStart">Start</button>
          <div id="tt">w3resource</div> 
        <button id="btnStop">Stop</button>    
       </div>

        
       
        
    </body>
</html>

Here is my code in JS (whose not working when im using if(event.target == btnStop){ } and let btnStop= document.getElementById("btnStop");):

window.onclick = function(event){
    


    let Startbtn = document.getElementById("btnStart");
    let btnStop= document.getElementById("btnStop");

    let getId= document.getElementById("tt"); //Any id name
    let getSstringToReplace = getId.childNodes[0].data;


    let myInterval 
    

    if(event.target == btnStart){   
        myInterval = setInterval(start, 100);
    }

    if(event.target == btnStop){   
          clearInterval(myInterval);
    }

    function start(){   
        getSstringToReplace= getSstringToReplace[getSstringToReplace.length-1] + getSstringToReplace.substring(0, getSstringToReplace.length - 1);  
        
        getId.childNodes[0].data = getSstringToReplace;
    }
    
}

but when i change that part of the code if(event.target == btnStop){ } and let btnStop= document.getElementById("btnStop"); , and add a new function stop() and change my getelementbyid to addEventListener, like here:

window.onclick = function(event){
    


    let Startbtn = document.getElementById("btnStart");
    document.getElementById("btnStop").addEventListener("click", stop);

    let getId= document.getElementById("tt");
    let getSstringToReplace = getId.childNodes[0].data;


    let myInterval 
    

    if(event.target == Startbtn){   
        myInterval = setInterval(run, 100);
    }
    function stop(){
        clearInterval(myInterval);
    }
    function run(){   
        getSstringToReplace= getSstringToReplace[getSstringToReplace.length-1] + getSstringToReplace.substring(0, getSstringToReplace.length - 1);  
        
        getId.childNodes[0].data = getSstringToReplace;
    }
    
} 

this one work, someone can explain why?

0

There are 0 answers