call function when user clicks outside of div - javascript

How can I call a function when the user clicks outside of a div?
The function is going to hide the div and some other elements on the page.

A simple example:
HTML
<div id="target">
Your div
<span>A span</span>
<div>
Another child div
</div>
</div>
jQuery
function hideDiv(e) {
if (!$(e.target).is('#target') && !$(e.target).parents().is('#target')) {
$('#target').hide();
}
}
$(document).on('click', function(e) {
hideDiv(e);
});
Working sample

Checkout the JQuery outside events plugin:
http://benalman.com/projects/jquery-outside-events-plugin/

Related

Javascript Function to Click Element that is Defined with Multiple Classes

I am trying to click a button but the only thing that defines it is multiple classes. The element I want to click is
<div class="U26fgb XHsn7e obPDgb M9Bg4d">This is a button </div>
How would I go about clicking it using Javascript?
As long as it is the only <div> element with that class combination, you'd use .querySelector(), which accepts any valid CSS selector as an argument so you can select elements in JavaScript the same way you would in CSS:
// Scan the document for the <div> that has the required classes
let theDiv = document.querySelector("div.U26fgb.XHsn7e.obPDgb.M9Bg4d");
// Set up a click event handling function
theDiv.addEventListener("click", function(){
console.log("you clicked me");
});
// Trigger the click event of the <div>
theDiv.click();
<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>
FYI: You should get out of the habit of putting spaces on the insides of the < and > delimiters in HTML. Use this:
<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>
Not this:
< div class="U26fgb XHsn7e obPDgb M9Bg4d" >Click Me< /div >
very simple with jQuery:
$(".U26fgb.XHsn7e.obPDgb.M9Bg4d").click(function(){
console.log("clicked!");
});
const div = document.querySelector('div .M9Bg4d');
div.addEventListener("click", ()=> {
// here put what you wanna do after clicking the div.
});
onclick attribute works well inside almost all the html tags and here is the simple solution to click on the div and get a result. All the Best!
function clickDiv(){
console.log("Div is Clicked");
}
<div class="U26fgb XHsn7e obPDgb M9Bg4d" onclick="clickDiv()">This is a button </div>

Make div clickable, only when anchor is present in div (multiple divs)

Given a basic structure how can I turn a series of divs into links without turning every div into a link? Here's an example:
<div class="boxes">
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
</div>
And the associated jQuery I'm using to make the divs clickable:
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
The problem I'm running into is the click function gets applied to all divs instead of only those with links.
The desired behavior is to only create a fully clickable div only when an anchor element is found.
For the purposes of this use case, the div (.box) is generated dynamically and wrapping the element in an anchor tag (<div> </div>) is not possible.
Fiddle: https://jsfiddle.net/fu8xLg0d/
Because you add event listeners on all the .boxes .box classes, which are all your divs.
Just add something like :
$(".boxes .box").has('a')...
to narrow it to those only containing an a element
JSFiddle
use .parent to solve your purpose:
$(document).ready(function() {
if($('.boxes p a').length){
$("a").parent().parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
But yes, it can even create a problem so i will say to give a class to your link and then call its parent... :)
Plotisateur just beat me by a minute or two! :P
if($('.boxes p a').length){
$(".boxes .box").has('a').click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
Here's the code anyway: https://jsfiddle.net/fu8xLg0d/1/
You can try this.
$(document).ready(function() {
var anchorbox =$(".boxes p a");
if(anchorbox.length>0){
$(anchorbox).parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
div (.box) is generated dynamically.
Delegate the click event from the body to the target div and on click on the element check if it has anchor tag. For adding the pointer icon create a separate function which will add the icon to the div only if it has an anchor tag as child
$(document).ready(function() {
// separate function to add pointer only if a is present
addClassToElem();
$("body").on('click', '.box', function() {
if ($(this).find('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
})
});
function addClassToElem() {
$('.box a').each(function(a, b) {
$(this).parent().addClass('linkIcon')
})
}
.linkIcon {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
</div>
This little change, helps you to resolve the issue.
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
});
}
});
the difference from your code is, additionally add a checking
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}

How to bind click event to element hasn't specific child using jquery?

I have several elements on a page like bottom code.
<div>
click
some content
</div>
They can be clicked and jQuery picks that click. However one of the elements has a a link that is clicked should not be picked as a click of the parent element.
$('div:not(#notme)').on('click', function(e) {
// do something
});
Doesn't seem to work for some reason...
Use :has selector to selecting div element has specific child. In :has use :not.
$("div:has(a:not(#notme))").on("click", function(e) {
console.log("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
click
some content
</div>
<div>
<a href="#" >click2</a>
some content 2
</div>
You may try:
$('div').on('click', function(e) {
if($(e.target).attr("id") !== "notme") {
// do something
}
});
$('#notme').on('click', function(e) {
e.stopPropagation();
});

How to make the js function "onClick" work only on the container div?

I got a problem with the onClick function. I have to set
display: none;
in a css container div when the user clicks on it, but not when he clicks on the divs which are in the container.
<div id="msg_background" onclick="javascript:closemsg();">
<div id="new_msg_cont">
</div>
</div>
So, i don't want that clicking on "new_msg_cont" the function still works.
Here's the js:
function closemsg() {
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
Thanks in advance.
This is called "bubbling" where the inner elements event 'bubbles' up to the parent element.
You can cancel this with event.stopPropagation():
Inline script
<div onclick="event.stopPropagation();" id="new_msg_cont"></div>
jsFiddle
External script
div onclick="javascript:cancel(event);" id="new_msg_cont"></div>
javascript:
function cancel(e)
{
e.stopPropagation();
}
jsFiddle
try something like this
javascript
function closemsg(event) {
if(event.target.id == "msg_background" ){
alert('you cliked me');
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
}
html
<div id="msg_background" onclick="closemsg(event);">
div1
<div id="new_msg_cont">
div2
</div>
</div>
Try this approach:
<div id="msg_background" onclick="javascript:closemsg(this);">
<div id="new_msg_cont">
... your code ...
</div>
</div>
JS CODE
function closemsg(ele) {
if(ele.id === 'msg_background'){
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
}
Inside your function check out if the event was fired by your parent div:
if (ev.target.id == "msg_background")
{
//execute the contents of the closemsg function
}
(ev is the event parameter)
Working Demo: http://jsfiddle.net/kVuKA/1/

Get the div id / class when windows.location is fired

I have a clickable div (windows.location) and I am trying to display a modal popup when this div is clicked.
here is my div box:
<div class="category_box" onclick="window.location='/Products/#cityName/#categoryName'">
<div class="category_box_catName">
#link
</div>
<div class="category_box_NumOfProds">
#Resources.Categories_GetByCity_NumProdsText
</div>
</div>
I was trying to get the class of this div when it clicked but could not make it work:
if ($(event.target).hasClass('div[class*=category_box]')) {
$('#mdlPopup').show();
}
Then I was trying to change the onclick and to add inside it $('#mdlPopup').show();
<div class="category_box" onclick="$('#mdlPopup').show(); window.location='/Products/#cityName/#categoryName'">
...
but this is also not working for me.
I removed the windows.location from the div and use this code to make the div clickable. then I can get the class from the div using:
$(document).ready(function () {
$('[class^=category_box]').click(function () {
$('#mdlPopup').show();
window.location = $(this).find("a").attr("href");
return false;
});
});

Categories