How to check if cursor is on a div - javascript

On clicking on a link I show a pop up. Here is my pop up code
<div class='' id="custom-popover">
<div class="arrow"></div>
<h3 class="popover-title">Popover left</h3>
<div class="popover-content" id="details-container">
</div>
</div>
</div>
I also add some html code using jquery when pop up show. Now I want to check if cursor is on this pop over or if user is hovering over this pop up and then I show an alert message otherwise hide the popup. How can I do this? I tried something like this
var isHovered = $('#custom-popover').is(":hover");
if (isHovered){
alert("msg");
} else {
$('#custom-popover').hide();
}
But this is not working. How can I do this?

use global variable:
var cursorOnDiv = false;
$(document).on({
mouseenter:function(){ cursorOnDiv = true; },
mouseleave:function(){ cursorOnDiv = false; },
},
'#yourDivId'
);
and check him

Try it:
$("#custom-popover").hover(
function() {
$("#custom-popover").show();
},
function() {
$("#custom-popover").hide();
});

Some thing like this,
$( "#custom-popover" ).mouseover(function() {
$('#custom-popover').hide();
});
the function is() as per doc is often useful inside callbacks, such as event handlers.
This function runs only once as it is not a callback. So in order to detect hover events use call backs.
You can have even like this if you want to have enter and leave both,
$( "custom-popover" )
.mouseenter(function() {
})
.mouseleave(function() {
})

This is what you ask:
$("#custom-popover").hover(
function() {
alert("Hovering now");
$("#custom-popover").show();
},
function() {
$("#custom-popover").hide();
});
You stored a value whether #custom-popover is being hovered or not at the time of execution, you did not bind an eventListener (hover) for the cause.

Try this:
if($('#custom-popover:hover'))
{
alert("msg");
}
else
{
$('#custom-popover').hide();
}

Related

Click outside menu to close it

Here's my function,
$(document).ready(function () {
$('.a').click(function () {
var here = $(this).next('.b');
if (here.is(":visible")) {
here.hide();
} else {
here.show();
}
return false;
});
});
So, whenever I click the button it opens a small tab on same webpage & whenever I click it again it closes it. But once I open the tab I can't close it by just clicking somewhere on webpage apart from tab. I have to click the button again to close it.
How can I close tab just by clicking somewhere on webpage also by on the button?
I end up searching for this on almost every project, so I made this plugin:
jQuery.fn.clickOutside = function(callback){
var $me = this;
$(document).mouseup(function(e) {
if ( !$me.is(e.target) && $me.has(e.target).length === 0 ) {
callback.apply($me);
}
});
};
It takes a callback function and passes your original selector, so you can do this:
$('[selector]').clickOutside(function(){
$(this).removeClass('active'); // or `$(this).hide()`, if you must
});
Nice, chainable, elegant code.
On document click, the closest helps to check whether the tab has been clicked or not:
$(document).click(function (e) {
if($('.b').is(':visible')&&!$(e.target).closest('.b').length){
$('.b').hide();
}
});
You want to check for a click on the body :
$("body").click(function(e) {
if(e.target.id !== 'menu'){
$("#menu").hide();
}
});
menu would be the id of the menu.
If the body is clicked and the id of the div clicked doesn't equal that of the menu, then it closes.
Check this implementation
jQuery(document).ready(function() {
$(document).on('click','body, #btn',function(ev){
ev.stopPropagation()
if(ev.target.id== "btn"){
if($('#modal').is(':visible')) {
$('#modal').fadeOut();
} else{
$('#modal').fadeIn();
}
} else {
$('#modal').fadeOut();
}
});
});
html, body {
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">
Click Me!
</button>
<div id="modal" style="background-color:red;display:none;">
BLA BLA BLA
</div>
To check if the clicked element is outside of a given container, i.e. a menu, we can simply check if the event target is a child of the container. Using JQuery -
$('body').click(function(e) {
if ( 0 === $(e.target).parents('#container-id').length ) {
/// clicked outside -> do action
}
})
you have to add a click listener to the parent element, like here:
$('.parent-div').click(function() {
//Hide the menus if visible
});
Also because click events bubbled up from child to the parent,
you can exclude the click on the child element to get bubbled up and count as the parent click too. you can achieve this like below:
//disable click event on child element
$('.child-div').click(function(event){
event.stopPropagation();
});

Using jquery to determine if any elements within a div was clicked

How can I tell using jQuery if an any element within a div (panel1) was clicked? I have this piece of code that I use to show/hide a popup:
$('body').click(function (e) {
if ($(e.target).attr('id') == 'link1') {
$('#panel1').show();
} else {
$('#panel1').hide();
}
});
The problem is that the popup (panel1) gets dismissed if I click on any control/element within panel1. I'd like to keep panel1 open unless an area outside panel1 is clicked (or if link1 is clicked again). How can I revise this code to achieve this? Thanks...
Try this
$('#panel1').click(function (e) {
e.stopPropagation();
//Other code if you want to execute anything on panel click.
});
$('body').click(function (e) {
if($("#panel1").is(":visible"))
$('#panel1').hide();
});
Make a following html markup:
<body>
<div id="div1">
... all the body content here
</div>
<div id="panel1">
</div>
I suppose the popup #panel1 is positioned out of normal flow anyway, so it is no problem.
Then in jquery use div1 instead of body and that's it :-)
$('body').click(function (e) {
if ($(e.target).attr('id') == 'link1') {
$('#panel1').show();
} else if($(e.target).attr('id') != 'panel1') {
$('#panel1').hide();
}
});

focus() doesn't work inside colorbox pop-up

I tried to use focus for first input field on the form. but
it doesn't work. When I call attr("id") for that input it worked. When I call focus for the same input, I didn't see any
result. I also tried to use native Javascript. Does anyone know how to
fix that?
You are all misunderstanding the question. When Colorbox opens you can't focus an input field?
...unless you add your focus to the Colobox onComplete key e.g.
$('#mydiv a').colorbox({ onComplete:function(){ $('form input:first').focus(); }});
You could also bind the focus to an event hook:
$('#mydiv a').bind('cbox_complete', function(){
$('form input:first').focus();
});
That should be enough to get started.
use
$(document).ready(function() {
// focus on the first text input field in the first field on the page
$("input[type='text']:first", document.forms[0]).focus();
});
It may be happening that when your colorbox is opened its focus goes onto the highest element i.e. body of page. use document.activeElement to find that focus went to which element. Then find iframe or id of your colorbox and then set focus on it
Try the first selector,
$("form input:first").focus();
http://jsfiddle.net/erick/mMuFc/
I've just stumbled on this problem.
I think it's best to have a single $.colorbox opener like this:
function showActionForColorBox(
_url,
_forFocus
) {
$.colorbox(
{
scrolling: false,
href: _url,
onComplete: function () {
idColorboxAjaxIndect1.appendTo($('#cboxOverlay'));
idColorboxAjaxIndect2.appendTo($('#cboxOverlay'));
idColorboxAjaxIndect3.appendTo($('#cboxOverlay'));
idColorboxAjaxIndect4.appendTo($('#cboxOverlay'));
// --> Possible element's ID for focus
if (_forFocus) {
$('#' + _forFocus).focus();
}
return;
},
onCleanup: function () {
// TODO: ?
return;
},
onClosed: function () {
if (shouldReloadPageAfterColorBoxAction) {
// --> Should we reload whole page?
shouldReloadPageAfterColorBoxAction = false; // NOTE: To be sure: Reset.
window.location.reload(false);
}
else if (cbEBillsActionReloadPopup) {
// --> Should we reload colorbox
cbEBillsActionReloadPopup = false;
showActionForColorBox(_url);
}
else if (cbShouldLoadAnotherContentAfterClosed) {
// --> Should we reload colorbox with custom content?
cbShouldLoadAnotherContentAfterClosed = false;
$.colorbox({ html: setupContentForcbShouldLoadAnotherContentAfterClosed });
setupContentForcbShouldLoadAnotherContentAfterClosed = '';
}
return;
}
}
);
return;
}
You can also use
$.colorbox({
...,
trapFocus: false
});
to disable focus inside colorbox

Jquery - call function when blur+clicking certain element?

I want to call a function when a certain field gets blurred, but only if a certain element is clicked. I tried
$('form').click(function() {
$('.field').blur(function() {
//stuff
});
});
and
$('.field').blur(function() {
$('form').click(function() {
//stuff
});
});
But neither works, I reckon it's because the events happen simultaneously?
HTML
<form>
<input class="field" type="textarea" />
<input class="field" type="textarea" />
</form>
<div class="click-me-class" id="click-me">Click Me</div>
<div class="click-me-class">Click Me Class</div>
jQuery
$('.field').blur(function() {
$('#click-me').click(function(e) {
foo = $(this).data('events').click;
if(foo.length <= 1) {
// Place code here
console.log("Hello");
}
$(this).unbind(e);
});
});
You can test it out here: http://jsfiddle.net/WfPEW/7/
In most browsers, you can use document.activeElement to achieve this:
$('.field').blur(function(){
if ($(document.activeElement).closest('form').length) {
// an element in your form now has focus
}
});
I have edited my answer because we have to take into account that the event is asigned every time.
It is not 100% satisfactory, and I don't recommend this kind of complicated way of doing things, but it is the more approximate.
You have to use a global variable to take into account the fact that the field was blurred. In the window event, it is automatically reset to 0, but if the click on "click-me" is produced, it is verified before the window event, becase window event is bubbled later, it happens inmediately after the "click-me" click event
Working code
$(window).click(function(e)
{
$("#result").html($("#result").html()+" isBlurred=0<br/>");
isBlurred=0;
});
var isBlurred=0;
$('.field').blur(function() {
$("#result").html($("#result").html()+" isBlurred=1<br/>");
isBlurred=1;
});
$('#click-me').click(function(e) {
if(isBlurred==1)
{
$("#result").html($("#result").html()+" clicked<br/>");
}
});
".field" would be the input and "#click-me" would be the element clicked only just once.

Live query plugin doesn't work with the visible attribute selector

I have the following running in the jquery ready function
$('[id$=txtCustomer]:visible').livequery(
function() { alert('Hello') },
function() { alert('World') }
);
I get an alert for the first time saying 'Hello' but the functions are not called onwards when i toggle this visibility of the textbox.
Please help.
The livequery "match/nomatch" events don't work with jQuery pseudoselectors like ":visible". They do work for class selectors.
An easy fix would be to also add a class when you show the item, and remove a class when you hide the item.
For example:
(html)
<input type="button" value="toggle"/>
<div id="item"
style="width:100px;height:100px;background-color:#ff0"
class="Visible">
</div>
(script)
$(function() {
$("#item.Visible").livequery(
function() {
alert("match");
},
function() {
alert("nomatch");
}
);
$("input").click(function() {
if ($("#item").is(":visible"))
$("#item").hide().removeClass("Visible");
else
$("#item").show().addClass("Visible");
});
});
A demonstration of this can be found here: http://jsbin.com/uremo

Categories