Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use stopPropagation in click event

I have an anchor inside a div with class "element".

<div class="element logout">
    <div class="subTop">
        <a href="home.jsp" onclick="return confirm('Do you want to logout?');">Log Out</a>
    </div>
</div>

I use the following code to handle logout.

jQuery(".element").click(function(e){
    var tmpHref=jQuery(this).not('.logout').find(".subTop>a").attr('href');
    if(tmpHref!=undefined&&tmpHref!=""&&tmpHref!=null)
    {
        window.location.href=tmpHref;
    }
    else
    {
        jQuery(this).find(".subTop>a").click();
    }
});

But my problem is the confirmation event triggers again and again. I think its because of the even propagation. After my research i find out I can use e.stopPropagation() from this post. But I cannot figure out how could this be used here.

EDIT The message 'Do you want to logout?' in confirm box is dynamically taken from the database, so I cant hard code it in the code.

like image 785
arjuncc Avatar asked Mar 18 '13 07:03

arjuncc


1 Answers

Try this:

HTML:

<div class="element logout">
    <div class="subTop">
        <a href="home.jsp" class="testa" >Log Out</a>
    </div>
</div>

jQuery:

jQuery(".element").click(function(e){
    e.preventDefault();
    if( confirm('Do you want to logout?'))
    {
        //console.log(jQuery(this).parents('.element'));return;
        if(jQuery(this).hasClass('logout'))
        {        
            window.location.href='logout.jsp';
        }
        else
        {
            window.location.href='home.jsp';
        }
    }
});

Test Fiddle: http://jsfiddle.net/e52QN/1/

like image 98
Rohan Kumar Avatar answered Oct 30 '22 07:10

Rohan Kumar