ALREADY ANSWERED MYSELF (See Answers)
So leading on from jQuery `[jQuery created Element].is(“:hover”)` Only Seems To Work In Chrome.
A bit more background:
I was trying to maintain hover when we moved from an element already in the DOM to an element added by jQuery's .append() method.
I was using .is(":hover"). This method was working fine in Chrome but no other browsers. As we found out (from the link above) it removed some time ago.
OLD :HOVER METHOD
var
hov = $("<div class=\"over\">I'm Over You</div>"),
box = $("<div>Result: WAITING</div>")
$("body").append(hov).append(box);
$("#MeHover").on('mouseleave', function(){
var d = new Date();
box.text("Result: " + hov.is(":hover").toString().toUpperCase() );
});
On the mouseleave listener, keep open if either the hovered or hoverer element are the relatedTarget
var $hovered = $('#MeHover');
var $hoverer = $("<div class=over>I'm Over You</div>");
$("body").append($hoverer);
$hovered.add($hoverer).mouseenter(function() {
$hoverer.fadeIn();
}).mouseleave(function(e) {
if (e.relatedTarget != $hoverer[0] && e.relatedTarget != $hovered[0])
$hoverer.fadeOut();
});
.over {
display: none;
position: absolute;
top: 20px;
left: 0;
right: 0;
background: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MeHover">
Hover Over Me
</div>
So I toyed with tracking the mouse and seeing if it was in the container, but it seemed too expensive and complex to implement. In the end, I decided to go for the .data() route as per the below.
I also have a fiddle demonstrating: https://jsfiddle.net/glenn2223/uk7e7rwe/
CODE
var
hov = $("<div class=\"over\">I'm Over You</div>"),
box = $("<div>Result: WAITING</div>");
$("body").append(hov).append(box);
$("#MeHover").add(hov).mouseenter(function () {
$("#MeHover").data("keepHover", 1);
hov.fadeIn();
}).mouseleave(function () {
$("#MeHover").removeData("keepHover");
CloseHover();
});
function CloseHover(){
clearTimeout(t);
var t = setTimeout(function () {
if ($("#MeHover").data("keepHover") != 1)
hov.fadeOut();
}, 300);
}
Related
Firefox represents a bug when I insert a select box on mouseenter event. The whole dropdown list is gone on hover. How can I fix this bug?
document.querySelector('#test').addEventListener('mouseenter',function(){
this.innerHTML = '<select><option value=1>2</option><option value=2>3</option></select>';
});
#test{
width: 100px;
height: 100px;
background-color: #000;
}
<div id="test"></div>
Here is an alternative approach where we can append to the <div> element. In this example, mouseenter may fire a lot, so I wrapped this code in a closure to execute once to demo appending once. You can surely craft this to your needs but this approach should allow a bit more functionality than overwriting the html of the element
JSFiddle Link
var append = (function(ele, node) { // execute once closure
var executed = false;
return function (ele, node) {
if (!executed) {
executed = true;
ele.appendChild(node);
}
};
})();
document.querySelector('#test').addEventListener('mouseenter', function() {
var that = this;
var node = document.createElement('select');
node.innerHTML = '<option value=1>2</option><option value=2>3</option>'
append(that, node);
});
I can't select a value in Chrome either so this wouldn't be just a Firefox bug I think.
Anyway here is a fix. Just load the select when it's not loaded on mouse enter.
document.querySelector('#test').addEventListener('mouseenter',function(){
if(this.innerHTML===""){
this.innerHTML = '<select><option value=1>2</option><option value=2>3</option></select>';}
});
I made a menu on html (on the side and 100% heigth, expandeable as in android holo)
<div id="menu">
<button class="menubutton"></button>
<button class="menubutton"></button>
</div>
The menu normally remains transparent and with a short width:
#menu {
background-color: transparent;
width: 8%;
}
The idea was to expand and color it on hover. It was easy:
#menu:hover {
background-color: blue;
width: 90%;
}
There is no problem untill here. I need the same effect on focus. There is no way in css to change parent css on child focus (neither hover by the way, but it is not needed, cuase i can use the entire menu hover).
So i used a script:
var menubuttonfocus = document.getElementsByClassName("menubutton");
for (i=0; i<menubuttonfocus.length; i++) {
menubuttonfocus[i].addEventListener("focus", function() {
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
});
menubuttonfocus[i].addEventListener("blur", function() {
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
});
}
The script works just fine, the problem is that when you trigger those events by focusing a button, the css of #menu:hover changes somehow and #menu does not change when hovering. I tried to solve this by doing something similar but with hover instead of focus:
menu.addEventListener("mouseenter", function(){
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
});
menu.addEventListener("mouseout", function(){
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
});
This works somehow, but it is REALLY buggy.
I tried also to select "#menu:hover,#menu:focus", but it doesn't work because the focus is on the button elements and not in #menu.
Please avoid jquery if posible, and i know it's asking for too much but a pure css solution would be awesome.
Probably helpful info: html element are created dinamically with javascript.
I can show more code or screenshot, you can even download it (it is a chrome app) if needed: chrome webstore page
Thanks.
SOLVED: I did what #GCyrillus told me, changing #menu class on focus via javascript eventListener. .buttonbeingfocused contains the same css as "#menu:hover". Here is the script:
var menubuttonfocus = document.getElementsByClassName("menubutton");
for (i=0; i<menubuttonfocus.length; i++) {
menubuttonfocus[i].addEventListener("focus", function() {
menu.classList.add("buttonbeingfocused");
});
menubuttonfocus[i].addEventListener("blur", function() {
menu.classList.remove("buttonbeingfocused");
});
}
if the problem is what I think it is - you forgetting about one thing:
When you focusing / mouseentering the .menubutton - you are mouseleaving #menu and vice-versa - so your menu behaviour is unpredictible because you want to show your menu and hide it at the same time.
solution is usually setting some timeout before running "hiding" part of the script, and clearing this timeout (if exist) when running "showing" part.
it will be something like this:
var menuTimeout;
function showMenu() {
if (menuTimeout) clearTimeout(menuTimeout);
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
}
function hideMenu() {
menuTimeout = setTimeout( function() {
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
}, 800);
}
//then add your listeners like you did - but put these functions as a handlers - like this:
menu.addEventListener("mouseenter", showMenu);
...
//in addition you need also "mouseenter" and "mouseleave" events handled on .menubuttons
Im trying to make a 'blanket' of divs containing child divs 150px high and 150px wide.
I want each child div to fade in 1 after the other after after a millisecond or so, opacity changing from 0, to 1.
I cant seem to figure out how this works, or how id do it though?
http://jsfiddle.net/CCawh/
JS
$(function(){
var figure = [];
w = 1500;
h = 450;
for(i = 0, i < 30, i++){
$('div').append(figure[].clone()).fadeIn();
}
});
Here is a working solution.
The problems in your code
in for(i = 0, i < 30, i++), you should use ';', not ',' . Use developer tools in your browser to catch such typos
In your code $('div').append(figure[].clone()).fadeIn(); , The fadeIn applies to $('div') as append() returns the calling object itself. You must replace it with $('<figure></figure>').appendTo('div').fadeIn('slow'); and to fadeIn items one by one you could set a timeout with incrementing delays
Add display: none; style to the figure to keep it hidden initially
Here is the full code.
$(function(){
for(i = 0; i < 30; i++){
setTimeout(function(){$('<figure></figure>').appendTo('div').fadeIn('slow');}, i*200);
}
});
Here is a fiddle to see it working http://jsfiddle.net/CCawh/12/
Try using greensock TweenLite http://www.greensock.com/get-started-js/.
It has staggerTo/staggerFrom action that does exactly what you are asking. TweenLite in conjunction with jQuery makes animation very easy.
This would be a possible solution (DEMO).
Use an immediate function and call it again n times in the fadeIn callback.
$(function(){
var figure = $('figure');
var counter = 0;
(function nextFade() {
counter++;
figure.clone().appendTo('div').hide().fadeIn(500, function() {
if(counter < 30) nextFade();
});
})();
});
You can use the following implementation as an example. Using setTimeout() will do the trick.
I've updated your jsfiddle here: http://jsfiddle.net/CCawh/5/
HTML:
<div class="container">
<div class="box"></div>
</div>
CSS:
.box {
display: none;
float: left;
margin: 10px;
width: 150px;
height: 150px;
background-color: #000;
}
JS:
$(function() {
var box = $('.box');
var delay = 100;
for (i = 0; i < 30; i++) {
setTimeout(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}
});
Note that in order for the element to actually fade in, it must be hidden in the first place, i.e. display: none; or .hide()
Here's perhaps a more robust solution without counters:
http://jsfiddle.net/CCawh/6/
for(var i = 0; i < 30; i++){
$('div').append($('<figure>figure</figure>'));
}
(function fade(figure, duration) {
if (figure)
figure.fadeIn(duration, function() { fade(figure.next(), duration); });
})($('figure').first(), 400);
By the way, clauses in for loops are separated using semicolons, not commas.
I hope someone can help me with this, I have this javascript code that toggles my body background
function changeDivImage() {
imgPath = document.body.style.backgroundImage;
if (imgPath == "url(images/bg.jpg)" || imgPath == "") {
document.body.style.backgroundImage = "url(images/bg_2.jpg)";
} else {
document.body.style.backgroundImage = "url(images/bg.jpg)";
}
}
I activate it with this link:
change
my problem is that it works fine in IE and firefox, but in chrome, the links work twice then stop working, it basically switches to bg_2.jpg then once clicked again switches back to bg.jpg then it never works again :/
also, is there an easier way to accomplish this? css only maybe? basically i have two body background pictures and i want to be able to click on the link to toggle 1, then click again to toggle 2 instead, then back to 1, etc...
lastly, how can i make the two backgrounds fade in and out? instead of just switch between the two?
Use CSS classes!
CSS Rules
body { background-image: url(images/bg.jpg); }
body.on { background-image: url(images/bg_2.jpg); }
JavaScript:
function changeDivImage() {
$("body").toggleClass("on");
}
If you want to fade, you will end up having to fade the entire page. Use can use jQuery's fadeIn and fadeOut.
Here is your solution:
(This also supports additional images).
var m = 0, imgs = ["images/bg.jpg", "images/bg_2.jpg"];
function changeDivImage()
{
document.body.style.backgroundImage = "url(" + imgs[m] + ")";
m = (m + 1) % imgs.length;
}
Here is the working code on jsFiddle.
Here is the jQuery version on jsFiddle.
UPDATE: CROSS-FADING Version
Here is the cross-fading jQuery version on jsFiddle.
You wouldn't want the whole page (with all elements) to fade in/out. Only the bg should fade. So, this version has a div to be used as the background container. Its z-depth is arranged so that it will keep itself the bottom-most element on the page; and switch between its two children to create the cross-fade effect.
HTML:
<div id="bg">
<div id="bg-top"></div>
<div id="bg-bottom"></div>
</div>
<a id="bg-changer" href="#">change</a>
CSS:
div#bg, div#bg-top, div#bg-bottom
{
display: block;
position: fixed;
width: 100%;
/*height: 500px;*/ /* height is set by javascript on every window resize */
overflow: hidden;
}
div#bg
{
z-index: -99;
}
Javascript (jQuery):
var m = 0,
/* Array of background images. You can add more to it. */
imgs = ["images/bg.jpg", "images/bg_2.jpg"];
/* Toggles the background images with cross-fade effect. */
function changeDivImage()
{
setBgHeight();
var imgTop = imgs[m];
m = (m + 1) % imgs.length;
var imgBottom = imgs[m];
$('div#bg')
.children('#bg-top').show()
.css('background-image', 'url(' + imgTop + ')')
.fadeOut('slow')
.end()
.children('#bg-bottom').hide()
.css('background-image', 'url(' + imgBottom + ')')
.fadeIn('slow');
}
/* Sets the background div height to (fit the) window height. */
function setBgHeight()
{
var h = $(window).height();
$('div#bg').height(h).children().height(h);
}
/* DOM ready event handler. */
$(document).ready(function(event)
{
$('a#bg-changer').click(function(event) { changeDivImage(); });
changeDivImage(); //fade in the first image when the DOM is ready.
});
/* Window resize event handler. */
$(window).resize(function(event)
{
setBgHeight(); //set the background height everytime.
});
This could be improved more but it should give you an idea.
There's a cleaner way to do this. As a demo, see:
<button id="toggle" type="button">Toggle Background Color</button>
var togglebg = (function(){
var bgs = ['black','blue','red','green'];
return function(){
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
document.getElementById('toggle').onclick = togglebg;
http://jsfiddle.net/userdude/KYDKG/
Obviously, you would replace the Color with Image, but all this does is iterate through a list that's local to the togglebg function, always using the first available. This would also need to run window.onload, preferably as a window.addEventListener/window.attachEvent on the button or elements that will trigger it to run.
Or with jQuery (as I notice the tag now):
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = ['black', 'blue', 'red', 'green'];
return function () {
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/1/
And here is a DummyImage version using real images:
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = [
'000/ffffff&text=Black and White',
'0000ff/ffffff&text=Blue and White',
'ffff00/000&text=Yellow and Black',
'ff0000/00ff00&text=Red and Green'
],
url = "url('http://dummyimage.com/600x400/{img}')";
return function () {
document.body.style.backgroundImage = url.replace('{img}', bgs[0]);
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/2/
This question already has answers here:
pure javascript to check if something has hover (without setting on mouseover/out)
(5 answers)
Closed 3 years ago.
How can I check whether the cursor is over a div on the html page with JQuery/Javascript?
I'm trying to get cursor coordinates to see if they are in the rectangle of my element. Maybe there are predefined methods?
UPD, don't say anything about hover events, etc. I need some method which will return true/false for some element at the page, like:
var result = underElement('#someDiv'); // true/false
I'm not really sure why you wish to avoid hover so badly: consider the following script
$(function(){
$('*').hover(function(){
$(this).data('hover',1); //store in that element that the mouse is over it
},
function(){
$(this).data('hover',0); //store in that element that the mouse is no longer over it
});
window.isHovering = function (selector) {
return $(selector).data('hover')?true:false; //check element for hover property
}
});
Basically the idea is that you use hover to set a flag on the element that the mouse is over it/no longer over it. And then you write a function that checks for that flag.
For the sake of completeness I will add a couple of changes that I believe will help a bit for performance.
Use delegation to bind the event to one element, instead of binding it to all existent elements.
$(document).on({
mouseenter: function(evt) {
$(evt.target).data('hovering', true);
},
mouseleave: function(evt) {
$(evt.target).data('hovering', false);
}
}, "*");
Add a jQuery pseudo-expression :hovering.
jQuery.expr[":"].hovering = function(elem) {
return $(elem).data('hovering') ? true : false;
};
Usage:
var isHovering = $('#someDiv').is(":hovering");
The simplest way would probably be to just track which element the mouse is over at all times. Try something like:
<div id="1" style="border:solid 1px red; width:50px; height:50px;"></div>
<div id="2" style="border:solid 1px blue; width:50px; height:50px;"></div>
<div id="3" style="border:solid 1px green; width:50px; height:50px;"></div>
<input type="hidden" id="mouseTracker" />
$(document).ready(function() {
$('*').hover(function() {
$('#mouseTracker').val(this.id);
});
});
and then your function is simply
function mouseIsOverElement(elemId) {
return elemId === $('#mouseTracker').val();
}
Can't you just check $(select).is(':hover') ?
I did this with custom function:
$(document).mouseup(function(e) {
if(UnderElement("#myelement",e)) {
alert("click inside element");
}
});
function UnderElement(elem,e) {
var elemWidth = $(elem).width();
var elemHeight = $(elem).height();
var elemPosition = $(elem).offset();
var elemPosition2 = new Object;
elemPosition2.top = elemPosition.top + elemHeight;
elemPosition2.left = elemPosition.left + elemWidth;
return ((e.pageX > elemPosition.left && e.pageX < elemPosition2.left) && (e.pageY > elemPosition.top && e.pageY < elemPosition2.top))
}