How to detect div and its children using window.onclick? - javascript

Example code:
window.onclick = function(event) {
if(event.target.matches('.myDiv')){
DO THIS
}
}
Understandably, this only checks if a click is made on myDiv specifically.
Without using <div onclick="function()"> and without hardcoding each of myDiv's children into the if statement, is there a way to check if a click is made on a div and any of its children?

Instead you should do:
var parent_div = document.getElementsByClassName(".myDiv");
parent_div.onclick = function(e) { /*DO SOMETHING*/ };
This way you directly check for a click on an element and all of its children instead of getting the click event from window and then checking whether it is the element which you want or not.

try like this:
window.onclick = function (event) {
if (event.target.classList.contains('myDiv')) {
event.target.remove();
}
}

Related

How to make an action on first click and another action on second click

My goal is to move a div element to the right side of the page on the first click and move it back to the left if I click it again and so on. How can I do this in javascript?
As enhzfelp said in their comment, the best solution would be to create a css class which moves your element to the right side of the page and to add / remove it with javascript.
If your goal is actually to perform one action and on next event call perform another, you can simply change a variable whenever the event is called.
Example code:
let right = false;
someElement.on('click', () => {
right = !right;
if (right) moveRight();
else moveLeft();
});
function moveRight() { ... }
function moveLeft() { ... }
You can also do this
<script>
var clickCount = 0;
function checkClick() {
if ( clickCount % 2 == 0 ) {
alert("first click");
} else {
alert("Second click");
}
clickCount++
}
</script>
<button onclick="checkClick()">Click me</button>
So, as I understood, you want to make so on click, the div element move to the opositive direction of left or right.
You can make this with an event listener, that listens to the click event and execute whatever you want on every click.
document.addEventListener('click', function(event) {
// your code that executes on every click
});
This event listener listens the click on all your webpage, so if you want to only listen the click when the use click your div, you need to get the div. There are several ways, but I recomend you to add an id to the div.
<div id="iAmYourElement"></div>
And then get the element in JavaScript
const element = document.getElementById("iAmYourElement");
element.addEventListener('click', function(event) {
// your code that executes on every click
});
Now that we have the way to deal with the click event, let's talk about the code that goes inside the listener.
One way to do this is creating two CSS classes, one is your div on the left and another whe div on your right. So, if we need the element to be on the right, we add the right-class, and if we need the div to be to the left, we add left-class and remove right-class.
Final javascript code will looks like that:
const element = document.getElementById("iAmYourElement");
let isDivOnLeft = true;
element.addEventListener('click', function (event) { // executes if you click on the div
isDivOnLeft = !isDivOnLeft // We negate the value of isDivOnLeft, so if it was true, it will now be false and vice versa.
if (isDivOnLeft) {
elementToRight()
} else {
elementToLeft()
}
});
function elementToRight() {
element.classList.remove("left-class")
element.classList.add("right-class")
}
function elementToLeft() {
element.classList.remove("right-class")
element.classList.add("left-class")
}
Hmm,
my English is kinda weak so I'll try my best to explain.
Let's assume that we have a div with id moveable
<div id="moveable"></div>
And we have button
<button id="move">Move</div>
And our goal is to move the div to the right in the first click, and in the second click, we will move it back to the right.
let button = document.getElementById("move");
let div = document.getElementById("moveable");
button.addEventListener("click", function () {
const dataMovedAttribute = div.getAttribute("data-moved");
if (dataMovedAttribute && dataMovedAttribute === "true") {
div.setAttribute("data-moved", "false");
div.style.float = "left";
} else {
div.setAttribute("data-moved", "true");
div.style.float = "right";
}
});
Checkout this example:
https://codesandbox.io/s/vigilant-rosalind-176by

javascript - Mouse Click on parent element , but prevent it's child element to fire event

How to define on child element, not to trigger an event,
like on .mouseclick = 'no-event' or : .mousedown = 'no-event'
with natural Javascript command?
So, it's parent will get the the first event before bubbling-up,
the parent element event will get e. target = e.currentTarget
I need to do it on some specific child elements, and some not.
On parent element the 'capture', does not give the correct behaviour
as mentioned above.
All other solutions I follow on the web, are giving many 'tricky' solutions
that don't work correctly.
var parentEl = document.getElementById('parent');
var childEl = document.getElementById('child');
parentEl.addEventListener('click', function(event) {
}, true)
childEl.addEventListener('click', function(event) {
}, true)
If you pass the true on eventListener it stops the event from bubbling.
You could give the children a custom class which determines it should be clickable or not.
Inside the callback function for it's parent container check which class the target is using and act accordingly.
Here's an example:
document.getElementById("container").addEventListener('click', function(e) {
if (e.target.className == "clickable") {
console.log("I should do something!");
} else {
console.log("I should NOT do something!");
}
});
<div id="container">
<div class="clickable">
this is clickable
</div>
<div>
this is not clickable
</div>
</div>

disable onclick event on div when clicking on inside <a> link (No js framework)

I have this piece of code:
<div id="mydiv" onclick="ajax_call()">
Mylink
</div>
I'd like ajax_call() to be called only when clicking on empty space inside div but not on "Mylink". Is it possible without any external javascript framework?
Moreover I have this piece of css:
div#mydiv:hover{
background-color: blue;
}
Is it possible to disable the :hover stylesheet when the cursor is placed over "Mylink" (in order to suggest that clicking on "Mylink" won't trigger ajax_call() but will take to myurl)?
Attach the function at child element with click event, After clicked on child element it's handler stops the immediate propagation, As a result ajax_call() will not be invoked.
HTML
<div id="mydiv" onclick="ajax_call()">
Mylink
</div>
javaScript
function ajax_call(){
alert("empt space");
}
//this function stops the propagation and not triggered above
//function when clicked on child element.
function notCall(event) {
event.stopImmediatePropagation();
return false;
}
DEMO
I'm not sure what you want but if I keep my imagination may be that this work, lucky !
$("div#mydiv a").hover(function(){
$(this).parent().css("background-color","transparent")
})
Sure, what you need is the event target || scrElement
Like
function ajax_call() {
var target = event.target ? event.target : event.srcElement;
if(target.id==="mydiv") { alert("good to go"); }
}
See : http://jsbin.com/qujuxufo/1/edit
Edit/Update ( missed the second part ) - Started to answer this before the q was closed - but might as well as it now ..
For the second part of the question - it is not possible to set parent elements in CSS ( it flows top to bottom ) - for that some more JS is needed.
See http://jsbin.com/cileqipi/1/edit
CSS
#mydiv:hover { background-color:green; color:#fff}
#mydiv.anchorhover, #mydiv.anchorhover:hover { background-color:white;}
Then JS
var _mydiv = document.getElementById("mydiv");
var _mydiv_anchors = _mydiv.getElementsByTagName("a");
function toggleClass() {
var addClass=true, cls="anchorhover";
if((_mydiv.className).indexOf(cls) >= 0){ addClass=false; }
if(addClass) {
_mydiv.className=_mydiv.className+=' '+cls;
} else {
/* remove */
_mydiv.className=_mydiv.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, '');
}
}
for(var i=0, len=_mydiv_anchors.length; i<len; ++i) {
_mydiv_anchors[i].onmouseover = toggleClass;
_mydiv_anchors[i].onmouseout = toggleClass;
}
^ That feels like quite a trip compared to how simple jquery abstracts it .. >
$("#mydiv a").hover(function() {
$(this).parent().addClass("anchorhover");
}, function() {
$(this).parent().removeClass("anchorhover");
});
Either way, the principle is : to add a style class to the parent element on mouseover and remove it on mouseout

attach an event to the body when ul is visible, then remove it when invisible

I have a <ul> that when clicked, toggles the visibility of another <ul>. How can I attach an event to the body of the page when the <ul>s are revealed so that the body will hide the <ul>.
I am new to writing these sorts things which bubble, and I cannot figure out why what I have done so far seems to work intermittently. When clicked several times, it fails to add the class open when the secondary <ul> is opened.
And of course, there may be an entirely better way to do this.
$(document).on('click', '.dd_deploy', function (e) {
var ul = $(this).children('ul');
var height = ul.css('height');
var width = ul.css('width');
ul.css('top', "-" + height);
ul.fadeToggle(50, function () {
//add open class depending on what's toggled to
if (ul.hasClass('open')) {
ul.removeClass('open');
} else {
ul.addClass('open');
}
//attach click event to the body to hide the ul when
//body is clickd
$(document).on('click.ddClick', ('*'), function (e) {
e.stopPropagation();
//if (ul.hasClass('open')) {
ul.hide();
ul.removeClass('open')
$(document).off('click.ddClick');
// }
});
});
});​
http://jsfiddle.net/JYVwR/
I'd suggest not binding a click event in a click event, even if you are unbinding it. Instead, i would do it this way:
http://jsfiddle.net/JYVwR/2/
$(document).on('click', function (e) {
if ( $(e.target).is(".dd_deploy") ) {
var ul = $(e.target).children('ul');
var height = ul.css('height');
var width = ul.css('width');
ul.css('top', "-" + height);
ul.fadeToggle(50, function () {
//add open class depending on what's toggled to
if (ul.hasClass('open')) {
ul.removeClass('open');
} else {
ul.addClass('open');
}
});
}
else {
$('.dd_deploy').children('ul:visible').fadeOut(50,function(){
$(this).removeClass("open");
})
}
});​
If you need to further prevent clicking on the opened menu from closing the menu, add an else if that tests for children of that menu.
You dont' really need all that code. All you need is jquery's toggle class to accomplish what you want. simple code like one below should work.
Example Code
$(document).ready(function() {
$('ul.dd_deploy').click(function(){
$('ul.dd').toggle();
});
});​​​​
Firstly, you are defining a document.on function within a document.on function which is fundamentally wrong, you just need to check it once and execute the function once the document is ready.
Secondly why do you want to bind an event to body.click ? it's not really a good idea.
Suggestion
I think you should also look at the hover function which might be useful to you in this case.
Working Fiddles
JSfiddle with click function
JSfiddle with hover function

jquery: get mouse click if inside a div or not

i have this HTML page
<html>
<body>
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
<div id='in_or_out'>e</div>
<div>f</div>
</body>
</html>
a,b,c,d,e and f could be divs also not just a plain text.
I want to get the mouse click event, but how could i know if it's inside or outside #in_or_out div ?
EDIT :: guys, i know how to check if the div is click or not, but i want my event to be fired when the click is outside that div
$("body > div").click(function() {
if ($(this).attr("id") == "in_or_out") {
// inside
} else {
// not inside
}
});
EDIT: just learned, that there is a negate:
$("body > div:not(#in_or_out)").click(function(e) {
// not inside
});
If you want to detect whether or not you've clicked inside or outside the div, set the event handler on the documentElement and let it propagate from the other elements upwards:
$("html").click(function (e)
{
if (e.target == document.getElementById("in_or_out"))
alert("In");
else
alert("Out!");
});
Maybe this one will help you
$('body').click(function(){
//do smth
});
$('div#in_or_out').click(function(e){
e.stopPropagation();
// do smth else
});
Depends what you want. If you only want to execute code, when it was inside #in_or_out, you can do:
$('#in_or_out').click(function(){ /* your code here */ });
You can have a status variable that says whether the mouse is in #in_or_out or not:
var inside = false;
$('#in_or_out').hover(function() { inside = true; }, function() { inside = false; });
Then whenever a click occurs you can check with inside whether the click was inside in_or_out or not.
Reference: .hover()
Update:
No matter to which element you bind the click handler, you can always do this:
$('element').click(function() {
if ($(this).attr('id') !== 'in_or_not') {
}
});
for inside it would be
$("#in_or_out").click(function() {
// do something here
});
for outside...I've got no idea.
Edit: You could try to do the same for body-tag (assigning a click-handler to the document itself). But I'm not sure if both events would fire by that.
Like this?
$("#in_or_out").click(function() {
alert("IN DIV!");
});

Categories

Resources