Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - anchor click

Tags:

jquery

I've got a working a.click() function in jquery... But if I click an anchor, I open an new window... But how can I stop the browser from opening a new window itself??

example:

    $('a').each(function() {
            $(this).click(function(e) {
                if($(this).attr('target') == '_popup') {
                    //here is code to open window (already exists)

                    //try to stop propagation, but doesn't work...
                    e.stopPropagation();
                }

                hideNSL();
            });
    });

so, how do I stop the event??

like image 602
dododedodonl Avatar asked Aug 20 '10 23:08

dododedodonl


People also ask

Can we use click on anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.

How do you trigger an anchor click?

If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works: $(document). on("click", "a", function(){ $(this). text("It works!"); }); $(document).

How hit an URL on a button click in jQuery?

Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.


4 Answers

Try

e.preventDefault()

but here return false may also do it which is in the other answer. preventDefault can be used in more senarios and is a more generic "stop the default event action", see: http://api.jquery.com/event.preventDefault/

like image 147
Lasse Espeholt Avatar answered Nov 15 '22 06:11

Lasse Espeholt


Add this to the end of your click event:

return false;

So for example:

$('a').each(function() {
        $(this).click(function(e) {
            var toReturn = true;
            if($(this).attr('target') == '_popup') {
                //here is code to open window (already exists)

                toReturn = false;
            }

            hideNSL();
            return toReturn;
        });
});
like image 29
Ender Avatar answered Nov 15 '22 05:11

Ender


You could try

e.preventDefault();
like image 28
MoDFoX Avatar answered Nov 15 '22 06:11

MoDFoX


e.preventDefault();
like image 23
Eton B. Avatar answered Nov 15 '22 07:11

Eton B.