How to make the whole div clickable? - javascript

I have a div with contents in it:
<div class="block">
<img src='...'>
<span>...</span>
</div>
I set up a JavaScript Event Listener when someone clicks on the div:
document.body.addEventListener("click", function(e) {
if (e.target.tagName === 'DIV' && e.target.classList.contains("block")){
(code)
}
}
It works when I click on the area of ​​the div that has no content. But it doesn't works, when I click to the image or to the text.
How can I get this at the whole div working?

The event.target is the element you clicked on. If you do not directly click on the div then your code will not match your tests because you are clicking on a child element.
So when you are using event delegation and you want to know if an element or one of its children is clicked on, you need to walk up the tree to see if it is that element. You can do that with closest
document.body.addEventListener("click", function(e) {
if (e.target.closest('div.block')) {
console.log('clicked', Date.now());
}
});
<h2>Example</h2>
<div class="block">
<img src='http://placekitten.com/g/200/300'>
<span>foo bar kitten</span>
</div>

Try to give an id to div and add your event listener to that.
<div id="myDiv" class="content">
// your content goes here
</div>
And in javascript
const myDiv = document.getElementById("myDiv");
myDiv.addEventListener("click", (event) => {
// your function goes here
})

There are many ways you can do it. But In my opinion the best way is to make anything clickable in JS is use onClick() function. You can simply use onClick=functionName()
function changeBackground(){
let block = document.getElementsByClassName('block');
block[0].style.backgroundColor = "green";
}
.block{
height: 50px;
border : 1px solid;
}
<div class="block" onClick="changeBackground()">
<div>

welcome to SO. You can add the event listener on the div itself and then perform whatever code you like. The reason it doesn't work in your case is because you are adding the event listener to the whole body and thus as the event handler is called, it doesn't recognize the elements you are clicking on even if they are inside the div.
Try this instead:
document.querySelector('div#block').addEventListener("click", function(e) {
// code...
});

Related

Ignore parent onclick when child onclick is clicked, using Javascript only

An good example of what im trying to do is, think of instragram. When you are click on a photo, it opens a window with that photo plus the grey background. If you click anywhere in the grey background the picture is closed, however if you click on the picture the picture remains in the window.
This is what I am trying to achieve with this:
<div class="overlay_display_production_list_background" id="overlay_display_production_list_background_id" onclick="this.style.display = 'none'">
<table class="table_production_availability" id="table_production_availability_id" onclick="this.parentElement.style.display = 'block'">
</table>
</div>
However this doesnt work. how do I get this working, I only want Purely java-script.
Thanks
Avoid intrinsic event attributes (like onclick). Bind your event handlers with JavaScript. Take advantage of the event object to prevent further propagation of the event up the DOM (so it never reaches the parent and thus doesn't trigger the event handler bound to it).
document.querySelector("div").addEventListener("click", parent);
document.querySelector("div div").addEventListener("click", child);
function parent(event) {
console.log("Parent clicked");
}
function child(event) {
event.stopPropagation();
console.log("Child clicked");
}
div {
padding: 2em;
background: red;
}
div div {
background: blue;
}
<div>
<div>
</div>
</div>
You perhaps can take an inner div which is absolute that has the background and certain height and width which is equal to main parent div and that has all the style, so on click of that div you may close parent div and on image you need not to do anything.
<div Parent><div Childdiv>
</div>
<img>
</div>
So childdiv should have display none functionality.
With JavaScript, you should be able to close parent div on a click of child div.

div onclick with Form and other elements

I want to fix a problem I have attaching an onclick element to a div ( and only to it! )
Please look at following code :
<script>
function goToo(url,idd){
alert(idd);
if (idd=="onlyMe")
window.location=url;
}
</script>
<div id="onlyMe" onclick="javascript:goToo('http://www.google.com', this.id)" style="<-index:-150">
<form><input type="text" name="coap"></form>
<h3>This is an element where click should work!</h3>
<div id="notME">
<h3>In this point it should not work!</h3>
</div>
</div>
I want the onlick to be triggered only in the div clicking.
Please check the example live # http://modacalcio.com/HtmlProblemForm.html
The click is triggered everywhere, expecially in the form input.
Obiovusly I wish to use this without deleting onclick in children nodes, as they have their own onclick that still need to work
Also with jquery I have same problem
any help?
$('#onlyMe').on('click', function(evt) {
if ($(evt.target).parents('#notME').length === 0 && evt.target.id !== 'notME') {
location.href = "http://...";
}
});
example fiddle: http://jsfiddle.net/zhkr2/2/
the idea is to check if the event was triggered on #notME element or inside an element contained in #notME, so I check if an ancestor is that element
just give for 'div' some width
#onlyMe
{
width:
height:
}
and close the div properly .

How to get top most parent Id when I click on any one of its child element?

I have the following HTML code:
<div id='parentDiv'>
<div class='firstDiv'>
<div class='firstDivChild1'></div>
<div class='firstDivChild2'>
<div class='firstDivChild2_Child1'></div>
<div class='firstDivChild2_Child2'></div>
</div>
</div>
<div class='secondDiv'>
<div class='secondDivChild1'>
<div class='secondDivChild1_child'>
<div class='secondDivChild1_child_child'></div>
</div>
</div>
</div>
</div>
Now my requirement is when I click on any div I want to get an top most parent Id (i.e. parentDiv). Presently I'm using the below script to get parent Id:
<script type='text/javascript'>
$('div').click(function(e){
var parentDivId = (e.target).parentNode.id;
alert(parentDivId );
});
</script>
but it doesn't work. Can anyone correct this code to reach my requirement?
If that parent DIV is unique across document, then you just can refer to it by ID, i.e. $('#parentDiv'), but if it's not, then you should change your HTML and add to parentDiv some class (i.e. parentDiv), and you'll be able to refer to it by this expression $(this).parents('.parentDiv:first');
$('div').click(function() {
alert($(this).parents('div').last().attr('id'));
return false;
});​
Live DEMO
then use the natural power of event bubbling. any descendant clicked will bubble up the event upwards (hence bubble) and will act as if the parent is clicked. so adding a click handler to the parent also does the same thing.
$('#parentDiv').on('click',function(){
var id = this.id
});
Try this little function :
$.fn.root = function() {
var $all = $( this[0] ).parents();
// omit "html", "body" and one index to the last item;
return $all.slice( $all.length - 3, $all.length - 2 );
};
Sample Usage :
$('input').click(function() {
alert($(this).root().prop('id'));
});​
Simple working example using your HTML here
It is still not completely obvious what you're asking for, but based on a few of your comments, here's my best guess.
Using event bubbling, you can examine all clicks in your document and you then determine where the click originated with e.target and you can then figure out whether that click originated in your div tree or elsewhere:
$(document).click(function(e) {
// determine if click was in our div tree or not
if ($(event.target).closest("#parentDiv").length) {
// click was in our parentDiv tree
} else {
// click was not in our parentDiv tree
}
});
Regardless of where the click was located, you can get the top of your div tree id="parentDiv" at any time with this with this jQuery:
$("#parentDiv")
If, you just want the top-most div that is above what is clicked, no matter where the click is in the document, you can use event bubbling like this to get that:
$(document).click(function(e) {
e.stopPropagation();
var topMostDiv = $(e.target).parents("div").last();
// do whatever you want with topMostDiv here
});

jQuery mouse event handling

I have following code:
HTML:
<div class="one">Content</div>
<div class="two">Content</div>
I want to hide my second div when mosueleave event happen from first div and also the mouse don't have over second div.
Algorithm:
if ((mouseleave from div.one) && (mouse not on div.two))
hide (div.two);
How can I implement this snippet using jquery? please help me.
You can set a flag on the .two div that keeps track of the mouseover state. Then when the mouse leaves .one you check for this state and if it exists you hide the div. Like so:
$(".two").live("mouseenter", function(){
$(this).data("hover", true);
}).live("mouseleave", function(){
$(this).removeData("hover");
});
$(".one").live("mouseleave", function(){
if( !$(".two").data("hover") ) $(".two").hide();
});
enclose both divs in another, say, div class='zero'. so you would have something in your $(document).ready() like
$('.zero').live('hover', function() {
$('.two').show();
});
$('.zero').live('blur', function() {
$('.two').hide();
});
note: you must style="display: none" for div class='two' by default

How to blur the div element?

I have a dropdown menu inside a DIV.
I want the dropdown to be hide when user click anywhere else.
$('div').blur(function() { $(this).hide(); }
is not working.
I know .blur works only with <a> but in this case what is the simplest solution?
Try using tabindex attribute on your div, see:
Check this post for more information and demo.
I think the issue is that divs don't fire the onfocusout event. You'll need to capture click events on the body and then work out if the target was then menu div. If it wasn't, then the user has clicked elsewhere and the div needs to be hidden.
<head>
<script>
$(document).ready(function(){
$("body").click(function(e) {
if(e.target.id !== 'menu'){
$("#menu").hide();
}
});
});
</script>
<style>#menu { display: none; }</style>
</head>
<body>
<div id="menu_button" onclick="$('#menu').show();">Menu....</div>
<div id="menu"> <!-- Menu options here --> </div>
<p>Other stuff</p>
</body>
$("body").click(function (evt) {
var target = evt.target;
if(target.id !== 'menuContainer'){
$(".menu").hide();
}
});
give the div an id, for instance "menuContainer". then you can check by target.id instead of target.tagName to make sure its that specific div.
Not the cleanest way, but instead of capturing every click event on the page you could add an empty link to your div and use it as a "focus proxy" for the div.
So your markup will change to:
<div><a id="focus_proxy" href="#"></a></div>
and your Javascript code should hook to the blur event on the link:
$('div > #focus_proxy').blur(function() { $('div').hide() })
Don't forget to set the focus on the link when you show the div:
$('div > #focus_proxy').focus()
I just encountered this problem.
I guess none of the above can fix the problem properly, so I post my answer here. It's a combination of some of the above answers:
at least it fixed 2 problems that one might met by just check if the clicked point is the same "id"
$("body").click(function(e) {
var x = e.target;
//check if the clicked point is the trigger
if($(x).attr("class") == "floatLink"){
$(".menu").show();
}
//check if the clicked point is the children of the div you want to show
else if($(x).closest(".menu").length <= 0){
$(".menu").hide();
}
});
.click will work just fine inside the div tag. Just make sure you're not over top of the select element.
$('div').click(function(e) {
var $target = $(e.target);
if (!$target.is("select")) { $(this).hide() };
});

Categories

Resources