detect visibility status of an element - javascript

Hi I would like to detect whether an element is visible or hidden. I thought about this
$("#mobile_navbar:visible").change(function() {
console.log("detected")
});
but this does not seem to work...? Any ideas how to do this? Basically I what to check whether $("#mobile_navbar").is( ":visible" ) has changed... but I want that a function is called whenever that happens, lick the .click() function which gets triggered if an element is clicked on.
thanks
carl

If you want to check that the element is visible on the screen, you can do like this :
if($(selector).css('visibility') == 'hidden') {
doSomething
}
else{
doSomethingElse
}

var isVisible = $("#mobile_navbar").css('display');
if(isVisible != 'none') {
console.log("detected")
};

Related

Simplifying Active States

I have a question that I believe comes down to method preference.
In the following code when the div parent element is clicked on, the div itself expands and also triggers an icon animation
var slideSection6 = document.getElementById("manualsHandbooks").addEventListener("click", function()
{
if (this.parentElement.style.height == "60px" || this.parentElement.style.height == "")
{
this.parentElement.style.height = "215px";
document.getElementById("MAHB").classList.add("active");
}
else
{
this.parentElement.style.height = "60px";
document.getElementById("MAHB").classList.remove("active");
}
}, false);
I was thinking about how easy it was just to add a class and change the state of the icon and I wanted to experiment and try adding the another click event just to the icon to make it animate on a click and active the parent element in the div as well. Basically the reverse of the above.
I thought it would be as simple as adding another condition to the if statement to the effect of
|| document.getElementId("MAHB").classList.add=("active") == true
But this doesn't work and I know it's not proper form. Could someone get me started so I could figure this out?
Element.classList has a toggle method that could make things a bit easier. If you want to check if a certain class is present, you can also use classList.contains.
I'd suggest not using the height of your elements to determine their current state. Why don't you alter the height using an active css class?
Your click handler could then be:
var button = document.getElementById("manualsHandbooks");
button.addEventListener("click", function() {
this.parentElement.classList.toggle("active");
document.getElementById("MAHB").classList.toggle("active");
}, false);
You can read more about classList here: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Get the first element that the mouse hovered after a MouseLeave event

Using jQuery/Javascript, how can I check which was the first element that the mouse hovered after a MouseLeave event?
Basically, I want to check from an array of elements if the mouse is rolling over those elements or not.
I'm trying to use the event.relatedTarget.
Any help?
There exists a relatedTarget property on the mouse events
The MouseEvent.relatedTarget read-only property is the secondary target for the mouse event, if there is one
and for the mouseleave it points to the element that was entered.
So you could just do
$('element').mouseleave(function(event){
// assuming that allowedList holds the array of allowed elements
if ( allowedList.indexOf( event.relatedTarget ) > -1 ){
// found
} else {
// not found
}
});
demo at http://jsfiddle.net/gaby/V4pJb/
Using jQuery, you can do this:
​$("#foo").mouse​​​leave(function(e) {
var element = $(e.target);
})​;​
Here's a working example. You can mouse over the text "Hello" and on mouseout, it will tell you which element it is leaving.
http://jsfiddle.net/k7Gfv/
If the mouseenter (or hover) is different from the mouseleave, then you'll need to track this using a variable. On mouseenter (or hover), set a variable that will store that element. On mouseleave, you can then reference that variable (just remember to clear or reset the value for the next time the mouseenter even is fired).
Not sure what you're looking for, but maybe it's somehing like this:
var elements = $("#a1, #a2");
$("#a3").on('mouseleave', nextElm);
function nextElm() {
$('div').on('mouseenter', thisIsIt);
$("#r").html('Now hover another element ?');
}
function thisIsIt(e) {
if ($.inArray(e.target, elements)!=-1){
$("#r").html('yes');
}else{
$("#r").html('no');
}
$("#a3").off('mouseleave', nextElm);
$('div').off('mouseenter', thisIsIt);
}
​
FIDDLE
You can do something like this. Here's a fiddle
var hovered = false;;
$('div').mouseleave(function(e) {
hovered = true;
});
$('div').hover(function(ev) {
if (hovered) {
alert(ev.target);
hovered = false;
}
});
​

Javascript: Clicking a wrapper element but not a child element

I am writing some javascript (jQuery) that enables a div wrapped around a checkbox, when clicked, will toggle the checkbox element. However, the problem I'm running into is that when you click on the checkbox, it doesn't work because it's being toggled twice (at least I think that's what's happening).
Here's a demo.
Here's the code:
$('.checkbox-wrapper').click(function(){
var $checkbox = $(this).find('input[type="checkbox"]');
if ($checkbox.is(':checked')) {
$checkbox.attr('checked', false);
} else {
$checkbox.attr('checked', true);
}
});
How can I make it so that clicking the checkbox works as normal, but if you click in the surrounding area, it toggles the checkbox?
Solution:
Thanks to jAndy's comment for showing how this can be done by checking the event.target property:
$('.checkbox-wrapper').click(function(e){
if( e.target.nodeName === 'INPUT' ) {
e.stopPropagation();
return;
}
var $checkbox = $(this).find('input[type="checkbox"]');
if ($checkbox.is(':checked')) {
$checkbox.attr('checked', false);
} else {
$checkbox.attr('checked', true);
}
});
And as others have pointed out, this may not be the best example since you get the same functionality (without needing javascript) by wrapping the checkbox with a label tag instead of a div tag. Demo
Check the event.target property.
The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling.
Try this
$('.checkbox-wrapper').click(function(e){
if(!$(e.target).is(":checkbox")){
var $checkbox = $(this).find('input[type="checkbox"]');
if ($checkbox.is(':checked')) {
$checkbox.attr('checked', false);
} else {
$checkbox.attr('checked', true);
}
}
});
Try just wrapping a <label> around it.
it sounds like you've not stopped the event bubbling up to the parent elements
How to stop event bubbling on checkbox click

If Mouseover Div Equals False - JQuery / Javascript

I'm trying to get this to work:
if($('#myDiv').hover() == false) {
myFunction();
}
Not getting much in the way of errors in Chrome or Firebug consoles. I've had a look at some other posts, and there was an answer that used something like:
if($('#myDiv').is(':hover') == false) {
myFunction();
}
However this also doesn't work.
Here's a jsfiddle if that helps: http://jsfiddle.net/yuwPR/2/
Any ideas greatly appreciated.
Thanks
EDIT:
Thanks for the answers, I wasn't able to get anything working. I'm thinking it might not be possible. Oh well, I'll try something else!
Thanks again
p.s. Most inventive answer marked as right and upvotes all round.
Without knowing your ultimate intent, you could wire up a hover on the document and check the current target.id
$(document).mouseover(function(event) {
if (event.target.id == "myDiv") {
$("body").css("background-color", "red"); //over the div so change the color
return;
}
$("body").css("background-color", "green"); //no on the div
});
code example on jsfiddle.
This code sample sets up a global js variable to store the hover state of the div. Then I use jquery hover to toggle that between true / false. Then, we just fire off a function every 10ms that checks the hover state. Currently I am just setting the window status telling you if you're hovered or not.
var _MOUSEOVER_IN_PROGRESS = false; //stores the hover state
function isover(){
if(_MOUSEOVER_IN_PROGRESS){
window.status = 'Still over!';
} else {
window.status = 'You are not hovering on me!';
}
setTimeout("isover()",10); //checking every 10ms!
}
$(document).ready(function(){
isover();
$('#mydiv').hover(
function(){ _MOUSEOVER_IN_PROGRESS = true; },
function(){ _MOUSEOVER_IN_PROGRESS = false; }
);
});
Edited my code! My mydiv hover catch was not wrapped in a document ready
The hover function takes 2 callback functions:
('#myDiv').hover(function () {
// function to call when hovering
},
function () {
myFunction();
}
);
So, when hovering is "false", ie, on mouse out, the second function will be called.
If you're only interested in doing something when the hover stops, you can use the mouseout() function:
$('#myDiv').mouseout(function() {
myFunction();
}
);
Your first call could never work:
$('#myDiv').hover()
This actually says "trigger the hover event on the element". It does not check to see if your user is currently hovering over the element.
Your second formulation should work:
$('#myDiv').is(':hover')
This checks to see if the element currently has the mouse hovering over it. However, it doesn't seem to work on document load. An example that works can be seen here. If you can clarify what you're trying to do, it might be possible to find some working code in this style.

How to simulate onclickout event with JavaScript

I'd like to somehow be able to define with JavaScript an onclickout event. That is something that happens when the user clicks anywhere else that the element in question.
I tried with onblur but it just don't seem to work :/
Is there any other way?
This uses the jQuery help, but the logic is the same if you prefer without it.
$(document).mouseup(function(event) {
var condition = $(event.target).parents(/* element_in_question */).length;
if (condition == 0) { // 0 means the event is not originated from the element in question
// Do what you need to do
}
}
});
document.getElementById('click').onclick = function(event) {
event.stopPropagation();
}
document.onclick = function() {
alert('click somewhere else');
}
jsFiddle.
This will send a click anywhere (except on #click) to the document.onclick handler, which will fire the alert().
You can set a variable, clickedin, on an element's click handler, and then have a click handler for the document that is checking if clickedin is true, and if it is, handle appropriately.
There may be a better way to accomplish the same end, though.

Categories

Resources