Two problems with jquery script: z-index and setTimeout - javascript

have a side menu on the left side of the website. I want the submenu to slide open to the right with a neat animation. I have made the script:
jQuery(document).ready(function($){
$(".main-navigation ul li").mouseenter(function() {
if ($(this).children().length > 0) {
$(this).children("ul").css ({
"display" : "block",
}).animate({
left: '250px',
opacity: 1,
}, 500)
}})
.mouseleave(function() {
setTimeout(function() {
$(this).children("ul").css({
"display" : "none",
"left" : "0px",
"opacity": 0,
})
}, 1000);
});
});
Sliding works just fine. The menu shows up nicely.
There's two problems though. One is, that the menu z-index doesn't work. The submenu's ul has a negative index set in css but when it slides it goes OVER the main ul. I want it to go UNDER the menu so it doesn't show.
Second one is, the SetTimeout function doesn't seem to work. Once the mouse leaves the area the ul just stays there forever. Without the Settimeout function it disappears just nicely (instantly though, I want it to stay there awhile).
I have made a jsfiddle example
http://jsfiddle.net/r8vx07ae/4/

Problem with z-index:
An element can not appear behind its parent. Since the submenu exists as a child element of the menu, it will not be able to appear behind the menu, z-index is really only applicable to two elements which share the same parent.
Problem with setTimeout:
The issue is most likely being caused because the this variable is out of scope by the time that the timeout occurs. This has an easy fix: create a global variable (say subMenu) and set subMenu = this before the timeout occurs and replace this with subMenu in your timeout function. You may use additional variables or a dictionary/array if you have multiple submenus to prevent the variable from being overwritten if two submenus get opened one right after the other

It is because $(this) is losing its scope on setTimeout function. To overcome this issue, you can assign your $(this) scope into a variable like $this and then use it in your setTimeout function. Here is the code changes:
.mouseleave(function() {
var $this=$(this);
setTimeout(function() {
$this.children("ul").css({
"display" : "none",
"left" : "0px",
"opacity": 0,
})
}, 1000);
});
And here is your updated fiddle:
http://jsfiddle.net/r8vx07ae/5/

The problem with the setTimeout is the scope of this
When it runs, it is the window, not the menu.
jQuery(document).ready(function($){
$(".main-navigation ul li").mouseenter(function() {
/* see if the timer has run yet, if it has not, cancel it */
var hideTimer = $(this).data("timer");
if (hideTimer) window.clearTimeout(hideTimer);
if ($(this).children().length > 0) {
$(this).children("ul").css ({
"display" : "block",
}).stop().animate({
left: '250px',
opacity: 1,
}, 500)
}})
.mouseleave(function() {
/* store the children here to get rid of the "this" scope issue */
var ul = $(this).children("ul");
/* Store a reference to the timer so we can cancel it if they mouseover again */
$(this).data("timer", setTimeout(function() {
ul.css({
"display" : "none",
"left" : "0px",
"opacity": 0,
})
}, 1000));
});
});
This will not fix the z-index issue.

I guess this is from the usage of "this" inside the callback of setTimeout sadly i do not have any computer to test out...
See section "the this problem": https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout#The_%27this%27_problem
To solve it, save a reference of this before the call of setTimeout, and use the saved reference inside your callback

Related

Javascript Accordian

I have a simple accordion working, except for one thing. I would like to be able to re-click the same accordion item again, and be able to set height to '0'.
Currently, the open accordion item closes when I click a different accordion item, which is exactly what I want to do — but I also want the ability to re-click the open accordion item and have that one close, when clicked. See working example below:
https://codepen.io/celli/pen/BaNLJWb
// set heights to 0
gsap.set('.content', {
height: 0
});
// click function
$('.accordianItem').click(function() {
if ($('.accordianItem').hasClass('on')) {
gsap.to($('.content'), {
duration: .25,
height: 0
});
$('.accordianItem').removeClass('on');
}
gsap.to($(this).children('.content'), {
duration: .25,
height: "auto"
});
$(this).addClass('on');
});
What code can I add to add this extra functionality?
I have modified your code by adding another if that checks if the element clicked has 'on' class already. It should now work as you intended it to (hide when the user clicks on the already opened header).
// set heights to 0
gsap.set('.content', {height:0});
// click function
$('.accordianItem').click(function() {
if($(this).hasClass("on")){
gsap.to($('.content'), {duration:.25, height:0});
$('.accordianItem').removeClass('on');
}
else{
if ($('.accordianItem').hasClass('on')) {
gsap.to($('.content'), {duration:.25, height:0});
$('.accordianItem').removeClass('on');
}
gsap.to($(this).children('.content'), {duration:.25, height:"auto"});
$(this).addClass('on');
}
});
You can do this much more simply than how you're currently doing it:
// Create the animation that you need
const tl = gsap.timeline({paused: true});
tl.to('.content', {duration: 0.25, height:0});
// Set the timeline to its end state
tl.progress(1);
// Toggle the timeline's direction
$('.accordianItem').click(function() {
tl.reversed() ? tl.play() : tl.reverse();
});
Demo
I highly recommend checking out the GreenSock forums. They're super useful and you can get quick help from people who are experts in GSAP and web animation :)

Using a jquery slider for text instead of images?

This may be a little too specific, but I have a jquery slider that I am using <p> classes instead of images to cycle through customer quotes. Basically the problem I am running into right now is when it is static and non moving (JS code is commeneted out) they are aligned how I want them to be. As soon as the JS is un commented, they stretch out of view and you just see a white box?
Any ideas?
How I want each panel to look like:
jsfiddle
So I sort of made this my Friday project. I've changed a whole lot of your code, and added a vertical-align to the quotes and authors.
Here's the fiddle http://jsfiddle.net/qLca2fz4/49/
I added a whole lot of variables to the top of the script so you could less typing throughout.
$(document).ready(function () {
//rotation speed and timer
var speed = 5000;
var run = setInterval(rotate, speed);
var slides = $('.slide');
var container = $('#slides ul');
var elm = container.find(':first-child').prop("tagName");
var item_width = container.width();
var previous = 'prev'; //id of previous button
var next = 'next'; //id of next button
Since you used a % based width I'm setting the pixel widths of the elements in case the screen is reszed
slides.width(item_width); //set the slides to the correct pixel width
container.parent().width(item_width);
container.width(slides.length * item_width); //set the slides container to the correct total width
As you had, I'm rearranging the slides in the event the back button is pressed
container.find(elm + ':first').before(container.find(elm + ':last'));
resetSlides();
I combined the prev and next click events into a single function. It checks for the ID of the element targeted in the click event, then runs the proper previous or next functions. If you reset the setInterval after the click event your browser has trouble stopping it on hover.
//if user clicked on prev button
$('#buttons a').click(function (e) {
//slide the item
if (container.is(':animated')) {
return false;
}
if (e.target.id == previous) {
container.stop().animate({
'left': 0
}, 1500, function () {
container.find(elm + ':first').before(container.find(elm + ':last'));
resetSlides();
});
}
if (e.target.id == next) {
container.stop().animate({
'left': item_width * -2
}, 1500, function () {
container.find(elm + ':last').after(container.find(elm + ':first'));
resetSlides();
});
}
//cancel the link behavior
return false;
});
I've found mouseenter and mouseleave to be a little more reliable than hover.
//if mouse hover, pause the auto rotation, otherwise rotate it
container.parent().mouseenter(function () {
clearInterval(run);
}).mouseleave(function () {
run = setInterval(rotate, speed);
});
I broke this in to its own function because it gets called in a number of different places.
function resetSlides() {
//and adjust the container so current is in the frame
container.css({
'left': -1 * item_width
});
}
});
//a simple function to click next link
//a timer will call this function, and the rotation will begin :)
And here's your rotation timer.
function rotate() {
$('#next').click();
}
It took me a little bit, but I think I figured out a few things.
http://jsfiddle.net/qLca2fz4/28/
First off, your console was throwing a few errors: first, that rotate wasn't defined and that an arrow gif didn't exist. Arrow gif was probably something you have stored locally, but I changed the 'rotate' error by changing the strings in the code here to your actual variables.
So, from:
run = setInterval('rotate()', speed);
We get:
run = setInterval(rotate, speed);
(No () based on the examples here: http://www.w3schools.com/jsref/met_win_setinterval.asp)
But I think a more important question is why your text wasn't showing up at all. It's because of the logic found here:
$('#slides ul').css({'left' : left_value});
You even say that this is setting the default placement for the code. But it isn't..."left_vaule" is the amount that you've calculated to push left during a slide. So if you inspect the element, you can see how the whole UL is basically shifted one slide's worth too far left, unable to be seen. So we get rid of 'left_value', and replace it with 0.
$('#slides ul').css({'left' : 0});
Now, there's nothing really handling how the pictures slide in, so that part's still rough, but this should be enough to start on.
Let me know if I misunderstood anything, or if you have any questions.
So, a few things:
1) I believe you are trying to get all of the lis to be side-by-side, not arranged up and down. There are a few ways to do this. I'd just make the ul have a width of 300%, and then make the lis each take up a third of that:
#slides ul {
....
width: 300%;
}
#slides li {
width: calc(100% / 3);
height:250px;
float:left;
}
2) You got this right, but JSFiddle automatically wraps all your JS inside a $(document).ready() handler, and your function, rotate needs to be outside, in the normal DOM. Just change that JSFiddle setting from 'onload' to 'no wrap - in head'
3) Grabbing the CSS value of an element doesn't always work, especially when you're dealing with animating elements. You already know the width of the li elements with your item_width variable. I'd just use that and change your code:
var left_indent = parseInt($('#slides ul').css('left')) - item_width;
$('#slides ul').animate({'left' : left_indent}, 1500, function () {
to:
$('#slides ul').stop().animate({'left' : -item_width * 2}, 1500, function () {
4) Throw in the .stop() as seen in the above line. This prevents your animations from overlapping. An alternative, and perhaps cleaner way to do this, would be to simply return false at the beginning of your 'next' and 'prev' functions if #slides ul is being animated, like so:
if ($('#slides ul').is(':animated')) return false;
And I think that's everything. Here's the JSFiddle. Cheers!
EDIT:
Oh, and you may also want to clearInterval at the beginning of the next and prev functions and then reset it in the animation callback functions:
$('#prev').click(function() {
if ($('#slides ul').is(':animated')) return false;
clearInterval(run);
$('#slides ul').stop().animate({'left' : 0}, 1500,function(){
....
run = setInterval('rotate()', speed);
});
});

Slide boxes with margin-left check if overslided

I made a simple content/box slider which uses the following javascript:
$('#left').click(function () {
$('#videos').animate({
marginLeft: '-=800px'
}, 500);
});
$('#right').click(function () {
$('#videos').animate({
marginLeft: '+=800px'
}, 500);
});
Here is the demo: http://jsfiddle.net/tjset/2/
What I want to do and I can't figure out how to show and hide arrows(left and right box) as the all the boxes slided.
So I clicked 4 time to the LEFT and slided all the boxes! then hide "left" so that you can't give more -800px
What can I do?
What you can do is check after the animation completes to see if the margin-left property is smaller or larger than the bounds of the video <div>. If it is, depending on which navigation button was clicked, hide the appropriate navigation link.
Check out the code below:
$('#left').click(function () {
// reset the #right navigation button to show
$('#right').show();
$('#videos').animate({
marginLeft: '-=800px'
}, 500, 'linear', function(){
// grab the margin-left property
var mLeft = parseInt($('#videos').css('marginLeft'));
// store the width of the #video div
// invert the number since the margin left is a negative value
var videoWidth = $('#videos').width() * -1;
// if the left margin that is set is less than the videoWidth var,
// hide the #left navigation. Otherwise, keep it shown
if(mLeft < videoWidth){
$('#left').hide();
} else {
$('#left').show();
}
});
});
// do similar things if the right button is clicked
$('#right').click(function () {
$('#left').show();
$('#videos').animate({
marginLeft: '+=800px'
}, 500, 'linear', function(){
var mRight = parseInt($('#videos').css('marginLeft'));
if(mRight > 100){
$('#right').hide();
} else {
$('#right').show();
}
});
});
Check out the jsfiddle:
http://jsfiddle.net/dnVYW/1/
There are many jQuery plugins for this. First determine how many results there are, then determine how many you want visible, then use another variable to keep track with how many are hidden to the left and how many are hidden to the right. So...
var total = TOTAL_RESULTS;
var leftScrolled = 0;
var rightScrolled = total - 3; // minus 3, since you want 3 displayed at a time.
instead of using marginLeft I would wrap all of these inside of a wrapper and set the positions to absolute. Then animate using "left" property or "right". There's a lot of code required to do this, well not MUCH, but since there are many plugins, I think you'd be better off searching jquery.com for a plugin and look for examples on how to do this. marginLeft is just not the way to go, since it can cause many viewing problems depending on what version of browser you are using.

Second animation not working

In an UL list do I want to animate the first LI inside. The first animation will remove the CSS class for the blue background and adds a new CSS to it to make it have a dark background. It also adds a new a line of code inside. The second animation will push the same div up with a fade on it so it disappears. Then it will get removed.
Both animations I have tested separated by commenting out the other animation and work proper.
The problem is that I can't run them together, if I do the first animation then the second animation won't work at all.
listTop = $('#ypPlaylist > ul li:first');
setTimeout(function ()
{
listTop.css('background', '#2d89ef').removeClass('bg-color-blue');
listTop.animate({ backgroundColor: '#1d1d1d' }, 300);
listTop.prepend('<b>Running: </b>').fadeTo(300);
}, 1000)
setTimeout(function ()
{
listTop.animate({ marginTop: '-=82px', opacity: 0 }, 800, function ()
{
listTop.remove();
});
}, 3000);
You can concatenate everything together, set a delay in between and remove the setTimeouts-function.
Checkout http://api.jquery.com/animate/ and http://api.jquery.com/delay/
There is also a short example $('#foo').slideUp(300).delay(800).fadeIn(400);

Why the box disappear immediately?

I want the mouseover on the coverImg then show the coverInfo
the coverInfo show the title and the description of the image
then the coverInfo do show
but I want the coverInfo stay and clickable when mouserover on itself
but it disappear immediately.
So what's the point I have missed?
The HTML
<div class="workshop_img">
<div class="coverInfo"></div>
<a href="#">
<span class="coverImg" style="background-image:url('images/work/show1.jpg')" title="Chictopia "></span>
</a>
The CSS:
.coverInfo {
position:absolute;
width: 200px;
height:200px;
background:rgba(0,0,0,0.5);
top:30%;
left:30%;
display:none;
}
see the jQuery code
$(function() {
$(".coverImg").each(function() {
//make the background image move a little pixels
$(this).css({
'backgroundPosition' : "-40px 0"
}).mouseover(function() {
$(this).stop().animate({
'backgroundPosition' : " -20px -60px "
}, {
duration : 90
});
//shwo the info box
var content = $(this).attr("title");
$("<div class='coverInfo'></div>").text(content).prependTo($(this).parent()).fadeIn("fast");
}).mouseout(function() {
$(this).stop().animate({
'backgroundPosition' : "-40px 0"
}, {
duration : 200,
});
$(this).parent().find(".coverInfo").stop().fadeOut("fast");
})
})
});
</div>
EDIT:
I have searched a lot and find something similar, I took them and the answer given below together to solve my problem, here is the code:
$(function() {
$(".coverImg").css({
'backgroundPosition' : "-40px 0"
}).mouseenter(function() {
var box = $(this).parents(".workshop_img").find(".coverInfo");
var content = $(this).attr("title");
var info = box.text(content);
$(this).stop().animate({
'backgroundPosition' : " -20px -60px "
},90);
info.show();
}).mouseleave(function() {
var box = $(this).parents(".workshop_img").find(".coverInfo");
var content = $(this).attr("title");
var info = box.text(content);
$(this).stop().animate({
'backgroundPosition' : "-40px 0"
},200);
info.stop().hide();
});
});
It has just been clean, but do not work fine.
What's the problem?
The new box shows immediately because it is not initially marked as hidden. .fadeIn() only fades in something that is initially not showing.
You can make it initially not visible like this:
$("<div class='coverInfo'></div>").text(content).hide().prependTo($(this).parent()).fadeIn("fast");
You also can get rid of the .each() iterator you're using. You don't need it. You can just use:
$(".coverImg").css(...).mouseover(...).mouseout(...);
You don't need the .each() at all.
I'd also suggest you use .hover(fn1, fn2) instead of .mouseover(fn1) and .mouseout(fn2).
And, it looks like you are creating a new object and inserting it on every mouseover event such that multiple such objects will pile up in the page. You should either .remove() the object in the mouseout function or you should reuse a previously existing element if it exists in the element rather than creating more and more of them.
Sometimes when you are using the events for mouse hovering and you are also changing the page, the change to the page can cause the element to lose the mouse hover which then hides the change to the page and then it all starts over again. I can't tell for sure if that is happening in your case (I'd need a working example to play with to see), but it seems possible.

Categories

Resources