2

I have a situation in which I am creating dynamic content from my database. In which I am creating <div> with content in it. And I have added onclick event that <div>. If user click on the content of the div which means on <div> it opens a popup window. But if there is a anchor tag in the content. At that time if user clicks on anchor tag, Both the event executes it also opens the link page and popup.

I want to prevent that div onclick when anchor tag is clicked.

Is there any this that can help me?

WarLock
  • 58
  • 6
  • Since your generating content serverside, or at least thats what is sounds like. Your best bet may be to add the onclick handler as an attribute. `onclick="return false;"` – user398371 May 20 '16 at 19:56

3 Answers3

2

if you use jQuery, try stopPropagation() function like this :

simple example :

$("div a").click(function(e) {
    e.stopPropagation();
    // your code here...
});

Or enhanced example with classes and IDs :

html :

<div id="content">
    ...
    <a href="/your/uri/here" class="noPropagation">my link</a>
    ...
</div>

js:

$("div#content a.noPropagation").click(function(e) {
    e.stopPropagation();
    // your code here...
});

here is documentation : https://api.jquery.com/event.stoppropagation/

Meloman
  • 3,558
  • 3
  • 41
  • 51
1

Since you're adding the <div> dynamically, you can bind a click event handler to the closest ancestor to the dynamic content. Here's one way to do it:

$('.some-container').on('click', 'div.dynamic-content a', function(event) {
    event.stopPropagation();
});
SimianAngel
  • 631
  • 10
  • 14
0

Here is an example https://jsfiddle.net/7c51j7av/

<div class="outer">
    <div class="inner">
    click me
    </div>
 </div>  



$(".outer").click(function(){
        alert("Here");
    });

    $(".inner").click(function(e){
        e.stopPropagation();
        alert("Stopped it");
    });
Zach
  • 1,964
  • 2
  • 17
  • 28