Clicking link inside div firing div's onclick - javascript

I have this simple issue: a div that contains a link, and the div has an onclick function defined. However, when I click the link, I just want to follow the link, and not fire the containing div's function.
Fiddle
HTML
<div>
Google
</div>
JQuery
$('div').click(function() {
alert("test");
});
CSS
div {
height: 100px;
width: 200px;
border: 1px solid red
}
So here, when I click the div, an alert is shown: that's fine. When the link is clicked, I don't want the alert to show.
How to avoid this?

You can apply event.stopImmediatePropagation(); to the link. According to the API, this keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree (https://api.jquery.com/event.stopimmediatepropagation/).
Here is the fiddle: http://jsfiddle.net/dxrdrqrc/

Related

Prevent underlying div onclick event to trigger

I'm trying to create an overlay which has an outer div (half see-through) and above an smaller inner content div. Clicking on the outer area makes the overlay dissappear. Clicking on the content area should interact with the overlay content.
Looking at my example code, clicking on the red area first raises an alert "red" and afterwards an alert "black" thus closing the overlay immediatly after the first interaction.
How can I prevent the onclick event of the underlying black div to trigger when the above red div is clicked?
<div onclick = "window.alert('black')" style = "background-color:black; width:100%; height:100%">
<div onclick = "window.alert('red')" style = "background-color:red; position: absolute; top:10%; left:10%; width: 80%; height: 80%;">
some content
</div>
</div>
I couldn't find anything online about that except people setting pointer-events to none which would disable the user to interact with the overlay content.
Also setting different z-indeices didn't work either.
If you want to verify the clickthrough happening: https://onlinegdb.com/rJbOmB0FV
This is more of a javascript behaviour you're experiencing.
Bubbling
The bubbling principle is simple.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
Use event.stopPropagation()
Definition and Usage
The stopPropagation() method prevents propagation of the same event from being called.
Propagation means bubbling up to parent elements or capturing down to child elements.
https://www.w3schools.com/jsref/event_stoppropagation.asp
Update
A simple function will be easier to handle.
Something like this:
const alert = (text) => {
event.stopPropagation();
window.alert(text)
}
<div onclick = "alert('black')" style = "background-color:black; width:100%; height:100%">
<div onclick = "alert('red')" style = "background-color:red; position: absolute; top:10%; left:10%; width: 80%; height: 80%;">
some content
</div>
</div>

Div with mouseEvent, with child div with mouse event - click outer div, get both events to fire

Let's say I have Div A, with a child Div B. Both have a mouse click assigned to them. How might I be able to click Div A, and have both Div A's and Div B's events triggered? I've looked into event bubbling but all my attempts to make this happen have failed so far.
I am assigning mouse events as such:
elem.addEventListener( 'click', myResponseFunction, true );
I tried setting the bubbling to true and false on both or one or the other and have had no success. Is this possible? No jQuery solutions please.
Further clarification:
Consider an expandable ad with tiles in the collapsed portion that can either be video or synopsis, determined at runtime from a data provider. I want the ad to expand when clicked anywhere in the collapsed portion, but if a "view video" button or "view synopsis" button is below the click-to-expand button, I'd like the ad to advance to the appropriate view after expanding. I desired a cleaner approach, if possible, than putting the expand action on each tile's call-to-action button. Each tile is a div with a background image and call-to-action button, all covered by and click-to-expand button.
Click events are only triggered on those elements that are under mouse/touch pointer.
Bubbling (up) means that once a child element has processed a click event it then triggers another event of the same type on it's parent element. This process repeats all the way up to the document element. What you want is bubbling down. Unfortunately that concept doesn't exist in JavaScript.
A pragmatic solution is to iterate over all child nodes and trigger click events manually when a parent node is clicked. There will be one side effect: mouse events bubble up by default and so when a child node is clicked, it's parent will also receive a click event. This can be easily solved by stopping event propagation further up inside of a child click event handler.
Here is a complete sample:
document.querySelector('.parent').addEventListener('click', function(e) {
console.log('hello from parent');
var children = this.children;
[].forEach.call(children, function(elem) {
elem.click();
});
});
document.querySelector('.child').addEventListener('click', function(e) {
e.stopPropagation();
console.log('hello from child');
});
.parent {
height: 300px;
width: 400px;
background-color: lightblue;
}
.child {
position: relative;
top: 100px;
left: 100px;
height: 100px;
width: 200px;
background-color: lightyellow;
}
<div class='parent'>
<div class='child'></div>
</div>

Setting up a call to external js class

It may be a simple question, but being a newbie it is hard to get it to run.
So I have this leanModal javascript class, which I want to use for a modal popup.
here is the example paragraph that has to appear once an image is clicked:
<p id="lean_overlay"> Some text to appear</p>
Following is the css that is applied to it:
#lean_overlay {
position: fixed;
z-index:100;
top: 0px;
left: 0px;
height:100%;
width:100%;
background: #000;
display: none;
}
The tutorial of leanModal class says the following:
Step 3: call the function on your modal trigger, as follows. Be sure to set the href attribute of your trigger anchor to match the id of your target element.
$("#trigger_id").leanModal();
What I want to be done is once an img is clicked, the leanModal method to be called, but I got lost in the previous tutorial, in particular which element is a modal trigger and which one is the target element. Moreover, how to call a function once an image is clicked?
any help is much appreciated.
Since you mentioned image is clicked, then you can check its target by
$('img').click(function (e) {
alert(e.target);
});

JavaScript: Expand area on click

What I'm trying to do is make it so that, when a user clicks in the textarea, it expands the div to show the 'Post' button.
Here's a picture of what I mean:
So, when the user clicks in the textbox area, I need the background div to expand and show the 'Post' button.
Here's the JSFiddle I started: http://jsfiddle.net/MgcDU/6018/
HTML:
<div class="container">
<div class="well">
<textarea style="width:462px" placeholder="Comment..."></textarea>
<button class="btn btn-primary" type="button">Post</button>
<div class="clearfix"></div>
</div>
CSS:
textarea {
margin-bottom: 0;
}
.btn {
float: right;
margin-top: 12px;
}
.container {
margin:20px 0 0 20px;
}
.well {
width: 476px;
padding: 12px;
}
I have no JavaScript experience, but I think this is a simple enough project to look at when finished to be able to understand the basics.
Add the following to your markup and styling and include the script.
HTML
<button class="btn btn-primary btn-toggle" type="button">Post</button>
CSS
.btn-toggle{
display: none;
}
Javascript
$("textarea").click(function(){
$(".btn-toggle").slideDown();
});
$(document).click(function(e){
e.stopPropagation();
if($(e.target).parents(".well").length == 0){
$(".btn-toggle").slideUp();
}
});
This segment of Javascript binds click event handlers to the textarea and the document. The event handler bound to the textarea simply slides down the button to make it visible.
The event handler bound to the document is fired on every click on the page since the click events propagate up the DOM to the document. Once the document fires the event, the handler checks to see if the target (aka element clicked) has a parent inside the well. If it does we do not perform any actions since we do not want to hide the button when the user clicks inside the textarea or the button itself. If the click is outside of the well we call the slideup function on the button to hide it in a stylish manner.
Working Example: http://jsfiddle.net/MgcDU/6025/
Kevin's answer is the one you want, but I was just feeling experimental with some CSS I had, so I just wanted to post it. This is a fadeInDown button. You may want to host the CSS on your website. I just used some code I had. You can change this fiddle to fadeIn or something else (just search Google for animate.css). http://jsfiddle.net/shaansingh/MgcDU/6024/embedded/result/

Javascript - Div Box as a HyperLink + Nested Text HyperLink - Possible?

Seeing as though Nested Anchor Tags are not possible, could Javascript be utilized to have a Div Box hyperlink to Page-A, while having a word of a Text within the Div Box hyperlink to Page-B?
Have tried working with the following Javascript (works for hyperlinking the Box or the Text, but not both):
<script type="text/javascript">
// Content-Link Click Events
$('.content-link-page-a').click(function(){
window.location.href = "page-a.html";
});
$('.content-link-page-b').click(function(){
window.location.href = "page-b.html";
});
</script>
Here's some CSS:
<style>
.box {
height: 50px;
width: 100px;
border: 1px solid #000;
}
</style>
And here's the HTML:
<div class="box content-link-page-a">
<div id="username" class="content-link-page-b">UserName</div>
</div><!--/box-->
You should remove the A from around the inner DIV, give it a bigger z-index than the outer, and handle the inner click event with calling event.stopPropagation to prevent bubbling of the event to the outer div. Here is a fiddle to solve the task.
Sample for the inner handler:
$('.content-link-page-b').click(function(e){
alert("page-b.html");
e.stopPropagation();
});
EDIT: In my comment above, I mentioned e.preventDefault() call. I didn't mean that, because that means the native DOM element's handler will be prevented, and not the jQuery event bubbling.

Categories