• I cannot add an event listener properly in javascript, and only alert boxes work. I am just testing to see if I can alert the src for and image when I click on a specific element. For example this does (kindof) work.

    function run(){
    	var el = document.getElementById('sliderjoint');
    	document.addEventListener("click", stuff(el));
    	}
    
    	function stuff(pic) {
    	alert(pic.src);
    		}	
    
    	window.onload = run;

    The problem with the above code is that this runs immediately after the page has loaded. It does not even recognize the click event.

    Without the last line of code (window.onload = run) it does not do anything at all.

    But the following code Does NOT work at all. Notice how when I set the event listener for the document, the code runs even though it is not exactly what I want. But when I set the event listener on an element, I get absolutely nothing. example:

    function run(){
    	var el =    document.getElementById('sliderjoint');
    el.addEventListener("click", stuff(el));
    }
    
    	function stuff(pic) {
    	   alert(pic.src);
    	}	
    
    	window.onload = run;

    This does not do anything at all. How do I set pure javascript event listeners to respond to a click on a specific element? I have done it multiple times before on non-wordpress sites, but WordPress makes it so difficult.

    My scripts are enqueued properly, i think:

    function sumcakes_scripts() {
    
    	wp_register_script('extrajs', get_template_directory_uri() . "/js/extra.js", array('jquery'));
    	wp_enqueue_script('extrajs');
    
    	}
    
    add_action('wp_enqueue_scripts', 'sumcakes_scripts');
  • The topic ‘javascript add eventListener not working properly’ is closed to new replies.