How to prevent a link from working on a child element? (jQuery)

Asked

Viewed 135 times

0

Imagine the following code below:

<a id="link" href="/nova_pagina.php">
    <div id="abrir-nova-pagina"     >Linha_1</div>
    <div id="nao-abrir-nova-pagina" >Linha_2</div>
<a/>

I want the a#link element to work when I click on the first div and open a new page and I don’t want the link to work when I click on the second div.

How can I do that?

I saw some examples with jQuery using the stopPropagation() method but it didn’t work.

Look below:

$('a#link').on('click', function(event){
    event.stopPropagation();
});

$('#nao-abrir-nova-pagina').on('click', function(event){
    alert('Funcionou!')
});

What I did wrong?

  • 1

    Young independent of anything this HTML structure is very wrong, even if you can make it work... A link is a link, "half link" makes no sense, there’s something wrong there...

  • Is missing the event.preventDefault();. You stopped the spread, but the link keeps opening. Soon, you will need to block the default action (open the link)...

  • @Lipespry did not understand

  • I was going to comment precisely on what @hugocsl said. Isn’t it better just to have Linha_1 be a link? The tag function a is to make all its content a link. If each line behaves differently (one is link, another is not), then they should not be within the same a

  • 1

    <a>&#xA; <div>Linha_1</div><a/> <div>Linha_2</div>

  • 1

    The a is also closed wrong. The correct would be </a> and not <a/>

  • I thought I’d comment on the structure of your code, as did the hugocsl. I also didn’t understand the need to "not open a link by clicking on the link"... We usually use some script associated with a link altogether. But simply answering your question, you already have an answer formulated by @Icaro Martins that matches exactly my previous comment.

Show 2 more comments

1 answer

0

the event.stopPropagation() goes to the propagation of the event (in case onClick) in other elements. In the example below if you comment on this code it, and click on div#nao-abrir-nova-pagina he will display the alert('funcionou') and then the alert(2).

the event.preventDefault() does it will not perform the standard action in this case the <a href>

$('a').on('click', function(event){
    alert(2);
});

$('#nao-abrir-nova-pagina').on('click', function(event){
    event.stopPropagation(); /// não propaga o click
    event.preventDefault(); /// não executa o <a href>
    alert('Funcionou!')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link" href="/nova_pagina.php">
    <div id="abrir-nova-pagina"     >Linha_1</div>
    <div id="nao-abrir-nova-pagina" >Linha_2</div>
<a/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.