$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});
Related
I'm trying to create a reusable function that works by hiding a specific div (outside the iframe) whenever a click is made anywhere inside an iframe.
To be more specific, this div I want to hide is a search menu that can be opened on top (z-index) of an iframe. I'd like to close this menu whenever I click outside it, which happens to be inside the full screen iframe.
I couldn't make it work using the solutions from this and other similar pages (Whenever I change the URL, it doesn't work anymore): Detect click event inside iframe
I managed to do something like this that works but the code is repetitive. I'd like a more general function that works whenever I click inside any iframe.
const iframeListener1 = addEventListener('blur', function() {
if (document.activeElement === document.getElementById('chrono-loader')) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframeListener);
});
const iframeListener2 = addEventListener('blur', function() {
if (document.activeElement === document.getElementById('plus-loader')) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframeListener);
});
const iframeListener3 = addEventListener('blur', function() {
if (document.activeElement === document.getElementById('google-docs-1-loader')) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframeListener);
});
const iframeListener4 = addEventListener('blur', function() {
if (document.activeElement === document.getElementById('google-sheets-2-loader')) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframeListener);
});
const iframeListener5 = addEventListener('blur', function() {
if (document.activeElement === document.getElementById('google-docs-3-loader')) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframeListener);
});
const iframeListener6 = addEventListener('blur', function() {
if (document.activeElement === document.getElementById('google-docs-4-loader')) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframeListener);
});
How can I trigger a function (to hide one specific div) whenever I click on any iframe?
Thanks in advance for any suggestions or help
Can save event listeners into a object and have a function to add them dynamically. That would mean to have some sort of html element which would have data-target attribute or similar. Additionaly can move the id_target to function parameter.
var iframe_listeners = [];
function add_iframe_event(){
const id_target = $('data-target element').data('target');
iframe_listeners[id_target] = addEventListener('blur', function() {
if (document.activeElement === document.getElementById(id_target)) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframe_listeners[id_target]);
});
}
Edit:
loop method
var iframe_listeners = [];
const ids = [ '1', '2' ];
for(const id of ids){
// skip if element doesnt exist
if($(`#${id}`).length == 0) continue;
add_iframe_event(id);
}
function add_iframe_event(id_target){
iframe_listeners[id_target] = addEventListener('blur', function() {
if (document.activeElement === document.getElementById(id_target)) {
$('#outer-layer-card').stop().fadeOut('fast');
}
removeEventListener('blur', iframe_listeners[id_target]);
});
}
I have several of these lines in my HTML:
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
I want to change the 'src' when one of them is clicked (but ONLY on that one)
I tried this but it does not work:
$(document).on('click', '.fave_icon', function (event) {
if ($(this).getAttribute('src') == "Iconos/heart.png")
{
$(this).src = "Iconos/heart_coloured.png";
}
else
{
$(this).src = "Iconos/heart.png";
}
});
this is the function you're in.
The clicked element is event.target. Replace $(this) with $(event.target) and it will work.
For the general case, where the targeted element has children, it's possible that the target of your click is a child (of .fave_icon). Use closest() to target the closest .fave-icon:
$(document).on('click', '.fave_icon', function(event) {
let elem = $(event.target).closest('.fave_icon');
if (elem.getAttribute('src') == "Iconos/heart.png") {
elem.src = "Iconos/heart_coloured.png";
} else {
elem.src = "Iconos/heart.png";
}
});
I ended up solving it like this:
<img src="Iconos/heart.png" onclick="fav(this);" alt="Fave" class="fave_icon">
And then
function fav(heart){
if (heart.getAttribute('src') == "Iconos/heart.png")
{
heart.src = "Iconos/heart_coloured.png";
}
else
{
heart.src = "Iconos/heart.png";
}
I am trying to get the tag name of the element clicked inside an li when the user clicks on the element. The li element is added dynamically to the HTML code. To do this I am using the code below however it does not seem to be working.
$('li *','div#contentWrapper').on('click','#interfaceContainer #left #sortableTestComponents li',function(e){
e.stopPropagation();
var domEl = $(this).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
Why is my code not working? Nothing happens when the user clicks on an element.
JSFiddle - http://jsfiddle.net/3FxQE/
Since you are interested in click events in li elements which comes under #interfaceContainer, the event registration must be $('#interfaceContainer').on('click','li',function(e){...});
Then to get the tagName, you need to use the actual source of the event this is available in e.target so you need to use $(e.target).get(0) to get the clicked dom element.
$('#interfaceContainer').on('click','li',function(e){
e.stopPropagation();
var domEl = $(e.target).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
Demo: Fiddle
You are trying to use a context where you don't need to, in your selector. Change $('li *','div#contentWrapper') with $('div#contentWrapper') and $(event.target) with $(e.target). A working fiddle is here
$('div#contentWrapper').on('click', '#interfaceContainer #left #sortableTestComponents li', function (e) {
e.stopPropagation();
var $this = $(this),
domEl = $this.get(0);
alert(domEl.tagName);
if (!$(e.target).hasClass("deleteTestComp")) {
var type = $this.find('div.headerName').html(),
information = $this.find('input[type=hidden]').val();
if (type == "CliSessionType") {
parseCliComponent(information);
} else if (type == "DBSessionType") {
parseDbComponent(information);
} else {
parseScreenComponent(information);
}
}
});
I want to detect in my firefox extension if a link has been clicked. So far, for this I add a click event listener to the window
window.addEventListener("click", function(event) { handleWindowClick(event); }, false);
...
handleWindowClick : function(event) {
if ("event.target is a link") {
// do something
}
};
For some links the event.target is simple the URL. However, for some links I get, e.g., a HTMLSpanElement as event.target. Am I on the right track to catch link clicks or are there other ways? If it works this way, how can I ensure the successfully test if the event.targer is a link?
You're adding an event listener to the main window which registers any click. The url's you're having problems with must be wrapped in a <span> tag. What you need is event delegation
Why don't you just put the click event listener to anchors (<a>)?
var hrefs = document.getElementsByTagName('a');
for (i = 0; i < hrefs.length; i++) {
hrefs[i].addEventListener(...)
...
}
or in jQuery:
$('a').click(function () {
...
});
check this out, i hope this is what you are looking for.
window.addEventListener("click", function(event) {
handleWindowClick(event);
}, false);
function handleWindowClick(event){
var origEl = event.target || event.srcElement;
if(origEl.tagName === 'A')
alert("anchor link is clicked");
else if(origEl.parentNode.tagName === 'A')
alert("clicked inside anchor");
else if(origEl.tagName === 'SPAN')
alert("span is clicked");
}
fiddle : http://jsfiddle.net/5zXkN/3/
I extended the answer of dku.rajkumar to support arbitrary constructs within "A"-tags. I'm simply go up the tree until I either find an "A" or I'm at the root (so no link clicked in this case). It seems to do the trick. Thanks to all for your help!
window.addEventListener("click", function(event) { handleWindowClick(event); }, false);
...
isLink : function(element) {
if(element.tagName === 'A')
return true;
else
if (element.parentNode)
return this.isLink(element.parentNode)
else
return false;
},
handleWindowClick : function(event) {
var element = event.target || event.srcElement;
var isLink = this.isLink(element);
if (isLink)
dump("A link has been clicked.\n");
},
I am using this code to check if an inputbox is empty or not and it works fine but it only checks check a key is press not when the page loads.
It's does what it should but I also want it to check the status when the page loads.
Here is the current code:
$('#myID').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
Try the following:
$(function() {
var element = $('#myID');
var toggleClasses = function() {
if (element.val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
};
element.on('keyup keydown keypress change paste', function() {
toggleClasses(); // Still toggles the classes on any of the above events
});
toggleClasses(); // and also on document ready
});
The simplest way to do is trigger any of the keyup,keydown etc event on page load. It will then automatically call your specific handler
$(document).ready(function(){
$("#myID").trigger('keyup');
});
try checking the value on a doc ready:
$(function() {
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
EDIT: just as an update to this answer, a nicer approach might be to use toggle class, set up in doc ready then trigger the event to run on page load.
function check() {
var $status = $('#status');
if ($(this).val()) {
$status.toggleClass('required_ok').toggleClass('ok');
} else {
$status.toggleClass('required_ok').toggleClass('not_ok');
}
}
$(function () {
$('#myID').on('keyup keydown keypress change paste', check);
$('#myID').trigger('change');
});
Well then why dont just check the field after the page is loaded?
$(document).ready(function(){
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
$(document).ready(function(){
var checkVal = $("myID").val();
if(checkVal==''){
$('#status').removeClass('required_ok').addClass('ok');
}
else{
$('#status').addClass('required_ok').removeClass('not_ok');
}
});