I was told previously that I should not bind events inside of a function. What would be my best option to get around this current issue? I click on a link and from that link I want to get some properties. Here is how I am currently doing it.
$(".portfolioLink").click(function(){
// Show slide and portfolio piece info
$(".inner-content.portfolio").show();
// Reset slides timer and pagination
clearInterval($('#slides').data('interval'));
$("ul.pagination li").removeClass("current");
// Get ID from link that is clicked.
var slideID = $(this).parent().attr("id");
$("#previous").click(function() {
slideID--;
clearInterval($('#slides').data('interval'));
$("ul.pagination li").removeClass("current");
portfolioSwitch(slideID);
});
$("#next").click(function() {
slideID++;
clearInterval($('#slides').data('interval'));
$("ul.pagination li").removeClass("current");
portfolioSwitch(slideID);
});
}
I have two buttons that go back and forth which are the next and previous buttons. Depending on what link I click, I want to go forward or back. What's the best way of having these click events outside of the $(".portfolioLink") click event and at the same time get those properties from the portfolio link?
Binding the click events inside another click event means that everytime a .portfolioLink is clicked, a new click function is bound to the #previous/#next button, so it would increment twice if .portfolioLink was clicked twice, three increments if clicked three times etc. You can use a variable in a higher to scope to solve the issue, like so:
var slideID = 0;
$(".portfolioLink").click(function() {
$(".inner-content.portfolio").show();
clearInterval($('#slides').data('interval'));
$("ul.pagination li").removeClass("current");
slideID = $(this).parent().attr("id");
}
$("#previous, #next").click(function() {
slideID = this.id=='next' ? slideID+1 : slideID-1;
clearInterval($('#slides').data('interval'));
$("ul.pagination li").removeClass("current");
portfolioSwitch(slideID);
});
I was told previously that I should not bind events inside of a function
It is not a problem to bind event handlers inside a function, only if that function is another event handler. If that other event handler would be executed multiple times (like in your case), you would bind (add) a new event handler every time which you normally don't want to do.
You can use a shared variable (a variable in a common scope)... if slideID is not set, don't do anything if #next or #previous are clicked:
var slideID;
$(".portfolioLink").click(function(){
// ...
// Get ID from link that is clicked.
slideID = $(this).parent().attr("id");
});
$("#previous").click(function() {
if(typeof slideID !== 'undefined') {
// ...
}
});
$("#next").click(function() {
if(typeof slideID !== 'undefined') {
// ...
}
});
Or you initialise slideID with a default slide number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With