Repeated execution of a jquery statement - javascript

Below, mentioned is a jquery code, where 'box1' is a div id and 'colors' is a class inside the modal dialog. However, it results in an unexpected behavior: When I click '.colors' for the first time, an alert box appears, but on clicking it the next time, two alert boxes appear(one after the other). That is, clicking for the nth time will result into 'n' alert boxes, one after another!
Please explain the analogous behavior and a possible solution.
$('#box1').click( function() {
window.location.href='#openModal';
$('.colors').click( function() {
alert('xyz');
});
});

You are assigning a new click event to .colors on every click of #box. You need to make use of .one():
$('#box1').one('click',function() {
window.location.href='#openModal';
$('.colors').on('click',function() {
alert('xyz');
});
});
This will only assign the click handler for .colors once. If you want the ability to click #box1 multiple times, then you need to combine your assignment with .off():
$('#box1').on('click',function() {
window.location.href='#openModal';
$('.colors').off('click').on('click',function() {
alert('xyz');
});
});
This will do allow multiple clicks of #box1 with only one click handler for .colors, because each time it unassigns and reassigns it. I don't recommend this, though, as its a lot of extra work for the DOM to do.

Yeah, you're re-binding click to the .colors class every time #box is clicked. You could fix it by unbinding the previous click events before rebinding. Like so:
$('#box1').click( function() {
window.location.href='#openModal';
$('.colors').off('click').on('click', function() {
alert('xyz');
});
});

Related

Nesting JQuery .click() events

I want to nest one .click() event with another but its not working. I looked at the .on() event, but I don't think its what I need. Below is basically what I have so far, but its not working as intended.
I want to click on the 'adress1' button, get directed to the next page where I either click the 'profession1' button or the 'profession2' button, and depending on which of the last two buttons is clicked, something respective happens.
//HTML code for first button
adress1
//HTML code on a different page for last two buttons
profession1
profession2
//Javascript/JQuery code
$("#adress").click(function(){
//Some action here based on #address click event
$("#profession-1").click(function(){
//Some action if #profession was clicked after #address
});
$("#profession-2").click(function(){
//Some other action if #profession2 was clicked instead
of profession1
});
});
Someone had told me to use the following:
$('#adress').on('click', '#profession-1', function() {alert("x1")}).on('click', '#profession-2', function() {alert("x2")});
but its not working either. I feel like my program is not registering the click.
Your help is much appreciated!
The "root" element, in this case #address, isn't a proper element to attach the click event. You want to attach to some parent element and target a child element. Events in JavaScript bubble up and trickle back down to the element that initiated the event Event Propagation.
To remedy the issue:
$('#someParentEl').on(
'click',
'#profession-1',
function() {alert("x1")}
).on(
'click',
'#profession-2',
function() {alert("x2")}
);
Further Reading:
http://www.quirksmode.org/js/events_order.html
https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation
http://learn.jquery.com/events/event-delegation/
The best way to accomplish something like this, is to have data attributes store whether or not something was clicked on... assuming this is a single page web app. Also make sure each id is unique, and referenced correctly for each click event.
address1
Then, when you click on that element, check if the data attribute is true or not on each click of the other elements.
$("#address").click(function(){
if($(this).attr("data-clicked") == "true") {
$(this).attr("data-clicked","false")
} else {
$(this).attr("data-clicked","true")
}
});
$("#profession-1").click(function(){
if($("#address").attr("data-clicked") == "true") {
//Some action
}
});
$("#profession-2").click(function(){
if($("#address").attr("data-clicked") == "true") {
//Some action
}
});
None of this was tested, but it should point you in the right direction.

jQuery one() limit?

I want to have a set of events the first time a specific element is clicked. Also, another set of events the first time another element is clicked.
Currently, just the first function is working. Nothing happens when I click the next element. No console errors, nothing.
$("#make-rect").one("click", function() {
$('.js-tour-1').addClass('hidden');
$('.js-tour-2').removeClass('hidden');
});
$(".elemRect").one("dblclick", function() {
$('.js-tour-2').addClass('hidden');
$('.js-tour-3').removeClass('hidden');
});

Change Div Class on click takes multiple clicks before it works

I used the methods in this question:
change div class onclick on another div, and change back on body click
So here's my jQuery function:
jQuery('.checkbox_wrapper').on('click', function(e){
jQuery(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
});
However it doesn't seem to be working properly. It takes multiple clicks before the class changes.
See my jsfiddle:
http://jsfiddle.net/7A3vw/
I cut it down to the bare essentials thinking it might be conflicting javascript, but even with the single function it takes multiple clicks before the class actually changes. Because the production environment has 1 click toggle a hidden checkbox, multiple clicks is not reasonable.
Could someone help me figure out what's causing this issue?
The click function fires twice, once for the image, and once for the input, as both will bubble to the parent element, and firing twice reverts the classes again (proof).
Just target the image instead, as that is what you're really trying to click, not the parent :
jQuery('.deck_card img').on('click', function (e) {
jQuery(this).closest('div').parent().toggleClass('not_selected selected')
});
FIDDLE
i guest you need the checkbox checked together with the toggling of your div.
$(document).ready(function(e) {
$('.checkbox_wrapper').on('click', function(e){
var checked = $(this).find('input[type="checkbox"]').is(":checked");
if(checked){
jQuery(this).parent().addClass('selected').removeClass('not_selected');
}else{
jQuery(this).parent().addClass('not_selected').removeClass('selected');
}
});
});
Your code is triggering click event twice. So use .preventDefault()
This makes the default action of the event will not be triggered.
$('.checkbox_wrapper').on('click', function(e){
$(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
e.preventDefault(); // prevent the default action to be
}); // triggered for next time
Check this JSFiddle
try this
jQuery(document).on("click",'.checkbox_wrapper', function(e){
jQuery(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
});
Multiple Clicks are getting triggered because you are using class selector. You need to use not to exclude extra elements :
jQuery("div.checkbox_wrapper :not('div.checkboxdiv')").on('click', function(e){
jQuery(this).parent()
.toggleClass('not_selected selected')
});
Here is a FIDDLE.

JQuery Event repeating in dynamic content

In a page of a website I'm making, the press of a button imports the contents of a another php page and appends it onto the page. However, that other page contains JQuery, and the click event($( ".ExpandRoleButton").click) repeats itself on previous elements every time I import the content. So if I add 3 elements;
Element 1: Repeats the click event 3 times
Element 2: Repeats the click event 2 times
Element 3: Runs the click event once
$("#AjouterPiece").click(function()
{
$.blockUI({ message: '<img src="images/ChargementGeant.gif"/><br/><h1>Un moment svp.</h1>' });
$.post("wizardincl/piste.php", {newPiste: newPiste}, function(data)
{
$("#wizardPistes").append(data);
$.unblockUI();
$(".divNewPiste").fadeTo(300, 1);
$("#nbExemplaires").attr("max", newPiste);
newPiste++
$( ".ExpandRoleButton").click(function()
{
if ($(this).hasClass('RetractRoleButton'))
{
$(this).find('img').attr('src', 'images/ExpandPetitNoir.png');
var that = $(this);
$(this).parent().parent().parent().parent().next().slideUp(500, function() {
that.parent().parent().parent().parent().css('border-bottom', '1px solid #FF790B');
});
$(this).removeClass('RetractRoleButton');
}
else
{
$(this).parent().parent().parent().parent().css('border-bottom', 'none');
$(this).find('img').attr('src', 'images/ExpandPetitNoirRetour.png');
$(this).parent().parent().parent().parent().next().slideDown(500);
$(this).addClass('RetractRoleButton');
}
});
});
});
Currently, part of the JQuery website seems down and after some search, I can't find anything to solve the problem. Is there any way to keep the code from repeating itself like this?
This is because you are binding the event to multiple event handlers. The first time #AjouterPiece is clicked, all .ExpandRoleButton buttons get binded to an onclick handler.
The next time #AjouterPiece is clicked, it gets binded again.
To prevent this, you must unbind the click handlers using the following code before binding it
$( ".ExpandRoleButton").unbind('click')
You can pass in the event with .click(function(e) {...}) and then call e.stopImmediatePropagation() to fire only the current handler, but that only addresses the symptom, not the real problem.
Edit: make sure you are only binding the new instance of the button by adding a context to your selector, like $('.ExpandRoleButton', data). Since you are matching on a class, that selector will grab all the buttons on the page; the context allows you to select only the one inside your result.
A good practice ( solely to prevent issues like this from occurring, unintended multiple click handlers added ) is to..
$(".selector").off('click').on('click', function...
or
$(".selector").unbind('click')...
$(".selector").bind('click')...

Jquery Content Cycle Next/Previous not working

I have a definition list with a lot of text inside of it. When a user comes to the page, I want the jQuery to hide two thirds of that content, add a next and previous button where appropriate, and fade the content in and out. The first third of the content is .issue-group-1, the second third is .issue-group-2, the third, .issue-group-3.
I am trying to set it so that when the user hits the next button, the next button changes classes, and thus acts differently the next time the user clicks it (that is, it takes them to the third page instead of the second.
Right now, the next/previous buttons are working on the first and second "pages" but the next button to the third page won't work.
My code is probably too long and this is maybe not the best way to do it--I'm new to jquery. Any suggestions would be helpful.
$(document).ready(function(){
$('.issue-group-2, .issue-group-3').hide();
$('a#next-button.page1').fadeIn(500);
$('a#next-button.page1').click(function() {
$(this).removeClass('page1').addClass('page2');
$('.issue-group-1').fadeOut(500, function() {
$('.issue-group-2').fadeIn(500);
});
$('a#previous-button').fadeIn(500);
});
$('a#previous-button.page2').click(function() {
$('#next-button.page2').removeClass('page2').addClass('page1');
$('.issue-group-2').fadeOut(500, function() {
$('.issue-group-1').fadeIn(500);
});
$('a#previous-button').fadeOut(500);
});
$('a#next-button.page2').click(function() {
$('a#previous-button').removeClass('page2').addClass('page3');
$('.issue-group-2').fadeOut(500, function() {
$('.issue-group-3').fadeIn(500);
});
$('a#next-button').fadeOut(500);
});
$('a#previous-button.page3').click(function() {
$(this).removeClass('page3').addClass('page2');
$('.issue-group-2').fadeOut(500, function() {
$('.issue-group-2').fadeIn(500);
});
$('a#next-button').fadeIn(500);
});
});
You need to use live instead of click. Check out the documentation.
$('a#next-button.page1').live("click", function() {...});
$('a#previous-button.page2').live("click", function() {...});
$('a#next-button.page2').live("click", function() {...});
$('a#previous-button.page3').live("click", function() {...});

Categories

Resources