mehulmpt
mehulmpt

Reputation: 16547

Onclick event to addEventListener not working

Check this code:

<script>
var next = document.getElementById("next");
var prev = document.getElementById("prev");

next.addEventListener("click",next(),false);
prev.addEventListener("click",prev(),false);

function next(e) {
e.preventDefault();
prev.style.display = "block";
next.style.display = "none";
}
function prev(e) {
e.preventDefault();
prev.style.display = "none";
next.style.display = "block";
}
</script>

<div id="nav">
<a href="javascript:void;" id="prev">&lsaquo;&lsaquo;&lsaquo;</a>
<a href="javascript:void;" id="next">&rsaquo;&rsaquo;&rsaquo;</a>
</div>

I don't know why this is not working. I'm loading script just before <body> tag. Please help.

It gives me error: Uncaught TypeError: Property 'next' of object [object Object] is not a function

Upvotes: 0

Views: 1895

Answers (2)

Aashray
Aashray

Reputation: 2753

You need to mention the function names. By specifying () along with the function name, they are called.

Change it to:

next.addEventListener("click",next,false);
prev.addEventListener("click",prev,false);

Upvotes: 0

adeneo
adeneo

Reputation: 318172

When you add the parenthesis to the functions, the functions are called immediately and the result, in this case undefined, is returned to addEventListener.

You want to reference the functions, not call them

next.addEventListener("click", next, false);
prev.addEventListener("click", prev, false);

The next error is that you're using the same names for the variables and functions, so when you say next.style it's now the function, not the element, as the function name overwrites the variable

var next_elem = document.getElementById("next");
var prev_elem = document.getElementById("prev");

next_elem.addEventListener("click", next_fn, false);
prev_elem.addEventListener("click", prev_fn, false);

function next_fn(e) {
    e.preventDefault();
    prev_elem.style.display = "block";
    next_elem.style.display = "none";
}

function prev_fn(e) {
    e.preventDefault();
    prev_elem.style.display = "none";
    next_elem.style.display = "block";
}

Upvotes: 4

Related Questions