Reputation: 11
After looking through all the JS docs out there, I just can't figure out why this isn't working: I've got a button with the ID of "next", and all I wanna do is trigger the function whenever the user clicks on that button.
var nextBtn = document.getElementById("next");
var nextSlide = function (a,b){
return a + b;
}
nextBtn.onclick = nextSlide(4,5);
So when the user clicks on the button, I can see the "9" in the console.
Upvotes: 0
Views: 79
Reputation: 829
Use
window.onload=function(){
var nextSlide = function (){
this.add=function(a,b){
console.log(a+b);
return a+b;
};
};
var nextBtn= document.getElementById('btn');
//nextBtn.attachEvent('onclick', new nextSlide().add(4,5)); //With versions less than IE9
nextBtn.addEventListener('click',new nextSlide().add(4,5), false); //IE9 and above
};
Upvotes: 0
Reputation: 25882
You can say like this
var nextSlide = function (a, b){
return function(){
return a+b;
}
}
var nextBtn = document.getElementById("next");
nextBtn.onclick = nextSlide(4,5); // so basically the clicking on button will call the function being returned by function nextSlide.
Upvotes: 0
Reputation: 721
You can use an anonymous function expression like this:
HTML
<button id="next">next button</button>
Javascript
var nextBtn = document.getElementById("next");
var nextSlide = function (a,b){
console.log(a + b); // for display purpose only
return a + b;
}
nextBtn.onclick = function(){
nextSlide(4,5);
}
Upvotes: 1