Ivo
Ivo

Reputation: 2636

Toggle only working the first time

I wrote this Jquery script to toggle a popup, now everything is working fine except for the part that the toggle is only working 1 time.

I saw it has something to do with the event bubbling initially and i need to do something with .stopPropagation(), only I'm not getting it fixed

$(function() {
    $(".nonrefundable a").on("click", function(e) {
        var link = this;

        e.preventDefault();
        $( "#popup" ).toggle();
        $("#ok").click(function () {
                    window.location = link.href;

        });
        $("#nope").click(function () {
            $( "#popup" ).toggle(); 

        });

    });
});

working code http://jsfiddle.net/Td42s/

Upvotes: 1

Views: 887

Answers (3)

Karan Adhikari
Karan Adhikari

Reputation: 362

Please Replace Your Js Code with This Code

$(function() {
    $(".nonrefundable a").on("click", function(e) {
        var link = this;

        e.preventDefault();
        $( "#popup" ).toggle();
        $("#ok").click(function () {
                    window.location = link.href;

        });
        $("#nope").unbind('click').click(function () {
           $( "#popup" ).toggle(); 

        });

    });
});

Hope this would help you

Upvotes: 0

j809
j809

Reputation: 1499

PROBLEM

You are putting your #nope and #ok click handler in wrong place.

This will assign handlers in each time you click anchor.

SOLUTION

So, you need to assign click handlers outside.

Do this:

$(function() {
    var link;
    $(".nonrefundable a").on("click", function(e) {
        link = this;
        $( "#popup" ).toggle();

    });
    $("#ok").click(function () {
        window.location = link.href;

    });
    $("#nope").click(function () {
        $( "#popup" ).toggle(); 

    });
});

Take a look at how it works:

DEMO

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : You are biniding click event to ok and nope when every time you click nonrefundatable anchor, just bind it once and change value of link variable inside click function of anchor.

Note : always put e.preventDefault() at the start of function

$(function() {
    var link ;
    $(".nonrefundable a").on("click", function(e) {
        e.preventDefault();
        link = this;
        $( "#popup" ).toggle();       
    });

    $("#ok").click(function () {
         window.location = link.href;        
    });

    $("#nope").click(function () {
        $( "#popup" ).toggle(); 
    });
});

Demo

Upvotes: 3

Related Questions