How to detect mouseleave() on two elements at once? - javascript

Answer can be in vanilla js or jQuery. I want to hide a div with the id "myDiv" if the user is no longer hovering over a link with the id "myLink" or a span with the id "mySpan". If the user has his mouse over either element "myDiv" will still show, but the second the user is not hover over either of the two (doesn't matter which element the user's mouse leaves first) "myDiv" will disappear from the face of existence.
In other words this is how I detect mouse leave on one element:
$('#someElement').mouseleave(function() {
// do something
});
but how to say (in a way that will actually work):
$('#someElement').mouseleave() || $('#someOtherElement').mouseleave()) {
// do something
});
How to detect this?

Something like this should work:
var count = 0;
$('#myLink, #mySpan').mouseenter(function(){
count++;
$('#myDiv').show();
}).mouseleave(function(){
count--;
if (!count) {
$('#myDiv').hide();
}
});
jsfiddle

You could use a multiple selector:
$("#someElement, #someOtherElement").mouseleave(function() {
// Do something.
});

You can beautifully use setTimeout() to give the mouseleave() function some "tolerance", that means if you leave the divs but re-enter one of them within a given period of time, it does not trigger the hide() function.
Here is the code (added to lonesomeday's answer):
var count = 0;
var tolerance = 500;
$('#d1, #d2').mouseenter(function(){
count++;
$('#d3').show();
}).mouseleave(function(){
count--;
setTimeout(function () {
if (!count) {
$('#d3').hide();
}
}, tolerance);
});
http://jsfiddle.net/pFTfm/195/

I think, it's your solution!!!
$(document).ready(function() {
var someOtherElement = "";
$("#someElement").hover(function(){
var someOtherElement = $(this).attr("href");
$(someOtherElement).show();
});
$("#someElement").mouseleave(function(){
var someOtherElement= $(this).attr("href");
$(someOtherElement).mouseenter(function(){
$(someOtherElement).show();
});
$(someOtherElement).mouseleave(function(){
$(someOtherElement).hide();
});
});
});
----
html
----
<div id="someElement">
<ul>
<li>element1</li>
<li>element2</li>
</ul>
</div>
<div id="tab1" style="display: none"> TAB1 </div>
<div id="tab2" style="display: none"> TAB1 </div>

While the answer from lonesomeday is perfectly valid I changed my html to have both elements in one container. I originally wanted to avoid this hence I had to do more refactoring for my clients in other html templates, but I think it will pay out on the long term.
<div id="my-container">
<div class="elem1">Foo</div>
<div class="elem2">Bar</div>
</div>
$('#my-container').mouseleave(function() { console.log("left"); });

Related

Efficient jQuery/JS - avoiding copy-paste the same code again & again

I need to write an efficient code in order to keep it simple & code file small, also I want to use the knowledge I hopefully get from here in future codes.
UPDATE: Just to be clear - my example is fixed "buttons" on browser window side & if you click on one of them, it takes you to div with same ID (look at code below).
IMAGE:
MY CODE EXAMPLE:
//Smooth Scroll Menu Links
jQuery('.div1').on('click', function(e) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:jQuery(this.hash).offset().top-100}, 800);
});
//I have to copy-paste it 1000 times & only change the ".div1" to something else
//Note that I need a solution with different class names, not "div1", "div2" etc but e.g "location", "potato", "car" etc.
How to make this code working without writing same lines for every single div?
There got to be a way to get class from item you click & then scroll to item with same name ID, right? Or any other way to keep codes shorter in that kind of situations - otherwise it's just copy-paste-huge-file fest.
You can give each button a class so you can catch them all, than go to the element you want to scroll to by looking at the attribute of the clicked button :)
HTML
<div class="buttons" data-scroll="div1">div1</div>
<div class="buttons" data-scroll="div2">div2</div>
<div class="buttons" data-scroll="div3">div3</div>
<div class="content" id="div1">some content</div>
<div class="content" id="div2">some content</div>
<div class="content" id="div3">some content</div>
JS
$('.buttons').on('click', function(e) {
e.preventDefault();
var scrollTarget = $(this).data("scroll");
scrollme(scrollTarget);
function scrollme(target) {
$('html,body').animate({scrollTop:$("#"+target).offset().top}, 800);
}
});
example: http://jsfiddle.net/7gd66kr1/1/
try this i hope will work with you :
jQuery('div').on('click', function(e) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:jQuery(this.hash).offset().top-100}, 800);
});
note that : this function will aplay on all divs in page
I think there are more than an unique solution. If you don't want to modify your HTML, then you need a condition to determine if the clicked element is an "active" one:
jQuery('div').on('click', function(e) {
var id = $(this).attr('class');
var scrollto = $('#' + id);
if(scrollto.length > 0) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:scrollto.offset().top-100}, 800);
}
});
If you "can" modify your HTML, it's wise to add some attribute to the "active" elements (the ones that are buttons), so you know they scroll the page, or put them inside a container. The attribute you add may be a class or any other valid attribute (I recommend "rel", but might be "data" as spotted by #Iliya Reyzis , who selects by class and scrolls to "data") and select them by it:
<div class="div1" rel="mybutton">div1</div>
jQuery("[rel='mybutton']").on('click', function(e) {
var id = $(this).attr('class');
var scrollto = $('#' + id);
e.preventDefault();
jQuery('html,body').animate({scrollTop:scrollto.offset().top-100}, 800);
});
Hope it helps!!

Loop through element and change based on link attribute

Trying to figure this out. I am inexperienced at jQuery, and not understanding how to loop through elements and match one.
I have 3 divs:
<div class="first-image">
<img src="images/first.png">
</div>
<div class="second-image">
<img src="images/second.png">
</div>
<div class="third-image">
<img src="images/third.png">
</div>
And off to the side, links in a div named 'copy' with rel = first-image, etc.:
...
Clicking the link will fade up the image in the associated div (using GSAP TweenMax)
Here is the function I've been working on to do this... but I am not fully understanding how to loop through all the "rel" elements, and make a match to the one that has been clicked on.
<script>
//pause slideshow on members to ledger when text is clicked, and show associated image
$(function() {
$('.copy').on('click','a',function(e) {
e.preventDefault();
var slideName = $(this).attr('rel');
$("rel").each(function(i){
if (this.rel == slideName) {
console.log(this);
}
});
//var change_screens_tween = TweenMax.to('.'+slideName+'', 1, {
//autoAlpha:1
//});
});
});
</script>
What am I doing wrong? I don't even get an error in my browser. :-(
Thanks to the answer below, I got farther. Here is my revised code.
$('[rel]').each(function(k, v){
if (v == slideName) {
var change_screens_tween = TweenMax.to('.'+slideName+'', 1, {
autoAlpha:1
});
} else {
var change_screens_tween = TweenMax.to('.'+slideName+'', 1, {
autoAlpha:0
});
}
});
});
This is starting to work, but makes the screenshots appear and then instantly fade out. And it only works once. Any thoughts?
Add brackets around rel, like so:
$('[rel]').each(function() {
if ($(this).attr('rel') == slideName) {
console.log(this);
}
});

How do I apply jQuery's slideToggle() to $(this) and do the opposite to all other elements?

What I'd like to do is have all elements of class collapsible_list not displayed by default (with one exception... see below*), and then toggle their display when their parent <div class="tab_box"> is clicked. During the same click, I'd also like for every other element of class collapsible_list to be hidden so that only one of them is expanded at any given time.
*Furthermore, when the page initially loads I'd also like to check to see if an element of collapsible_list has a child a element whose class is activelink, and if there is one then I'd like that link's parent collapsible_list element to be the one that's expanded by default.
Here's some sample html code:
<style>
.collapsible_list {
display: none;
}
.collapsible_list.active {
display: block;
}
</style>
<div id="sidebar">
<div class="tab_box">
<div class="collapsible_tab">2014</div>
<div class="collapsible_list panel-2014">
1
2
3
</div>
</div>
<div class="tab_box">
<div class="collapsible_tab">2013</div>
<div class="collapsible_list panel-2013">
<a class="activelink" href="/2013/1">1</a>
2
3
</div>
</div>
</div>
And here's where I'm currently at with the javascript (although I've tried a bunch of different ways and none have worked like I'd like them to):
$(document).ready(function() {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active");
$(".tab_box").click(function() {
$(this).children(".collapsible_list").toggleClass("active").slideToggle("slow", function() {
$(".collapsible_list.active:not(this)").each(function() {
$(this).slideToggle("slow");
});
});
});
});
I hope that's not too confusing, but if it is then feel free to let me know. Any help is much appreciated.
Since you have a dom element reference that needs to be excluded use .not() instead of the :not() selector
jQuery(function ($) {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active").show();
$(".tab_box").click(function () {
var $target = $(this).children(".collapsible_list").toggleClass("active").stop(true).slideToggle("slow");
//slidup others
$(".collapsible_list.active").not($target).stop(true).slideUp("slow").removeClass('active');
});
});
Also, instead of using the slide callback do it directly in the callback so that both the animations can run simultaniously
Also remove the css rule .collapsible_list.active as the display is controlled by animations(slide)
Try This.
$('.collapsible_tab a').on('click', function(e){
e.preventDefault();
$('.collapsible_list').removeClass('active')
$(this).parent().next('.collapsible_list').toggleClass('active');
});
Fiddle Demo
I think your code would be less complicated if you simply remembered the previously opened list:
jQuery(function($) {
// remember current list and make it visible
var $current = $('.collapsible_list:has(.activelink)').show();
$(".tab_box").on('click', function() {
var $previous = $current;
// open new list
$current = $('.collapsible_list', this)
.slideToggle("slow", function() {
// and slide out the previous
$previous.slideToggle('slow');
});
});
});
Demo

JQuery .not(next) - is it possible?

Example HTML:
<div class=blah>
<div class=moreCats></div>
</div>
<div class=subCats>.......</div>
<div class=blah>
<div class=moreCats></div>
</div>
<div class=subCats>.......</div>
<div class=blah>
<div class=moreCats></div>
</div>
<div class=subCats>.......</div>
Using slideToggle, if I click the first div moreCats I want next subCats to slideDown, which it does. At the same time I want to slideUp any other open subCats, but, NOT the one I'm toggling or else it would close then reopen, which is what its doing.
Question: is this valid? If not is there something similar?
$('div.subCats').not($(this).next('.subCats')).slideUp();
Here's the full JQuery I'm trying
// show children cat items
$('#sideNav').on("click", ".moreCats", function() {
$('div.subCats').not($(this).next('.subCats')).slideUp(); // close all except next
$(this).next('.subCats').slideToggle(); // slideToggle next
});
You can combine them by placing the slideToggle for the current target (which will return that element) inside .not and you want to select the parent's next as well
$('#sideNav').on("click", ".moreCats", function() {
$('div.subCats').not($(this).parent().next('.subCats').slideToggle()).slideUp();
//or do $(this).closest('.blah').next('.subCats');
});
Demo
If you want to split them, then better cache the next instead of selecting it again.
$('#sideNav').on("click", ".moreCats", function() {
var $target = $(this).parent().next('.subCats');
$('div.subCats').not($target.slideToggle()).slideUp();
//or just do as below
//$('div.subCats').not($target).slideUp();
//$target.slideToggle()
});
.moreCats doesn't have any siblings so you can't use .next(). What you really need is to get the next sibling of this's parent. So you go from $(this) > .parent() > .next('.subCats')
$('body').on("click", ".moreCats", function() {
console.log($(this).parent().next('.subCats'));
$('div.subCats').not($(this).parent().next('.subCats')).slideUp(); // close all except next
$(this).parent().next('.subCats').slideToggle(); // slideToggle next
});
See this JSFiddle for an example.
What you have is valid but it doesn't do what you expect, .next() selects the next immediate sibling element, you should first select the parent element:
$('div.subCats').not($(this.parentNode).next('.subCats')).slideUp();
You can also use .index() method:
$('#sideNav').on({
click: function() {
var $sub = $('div.subCats'),
i = $('#sideNav .moreCats').index(this);
$sub.not( $sub.eq(i).slideToggle() ).slideUp();
}
}, ".moreCats");

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

Categories

Resources