Chaining methods in jquery [duplicate] - javascript

This question already has answers here:
Jquery delay execution of script
(2 answers)
Closed 4 years ago.
I'm trying to make an animation by adding a class pressed then wait for 100ms then remove the class.
when I just add the class
$("#" + currentColor).addClass("pressed");
the code works fine. But when I chain the methods or write them separately none of the methods work.
$(".btn").on("click", function () {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
});
function animatePress(currentColor) {
$("#" +
currentColor).addClass("pressed").delay(100).removeClass("pressed");
}
I expect it to add the class pressed then wait 100ms then remove the classpressed. But it doesn't do anything. I also don't get any error report in the console

That is because the delay method only delays effects, such as fadeIn. It will not delay adding or removing classes. You should use setTimeout for that.
$(".btn").on("click", function () {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
});
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
window.setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}

You can use setTimeout() method for delaying the second action.
Your code should be like this:
$(".btn").on("click", function () {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
});
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function(){
$("#" + currentColor).removeClass("pressed")
},100)
}

Related

Mouseover for 1 second before triggering the event

I've written a simple bit of code that shows a div on a mouseover event. I'd like to mouseover the element for 1s before the event takes place. Any ideas on how I can achieve this? with a brief explanation if possible so I know for next time.
$('.NavSelect h2').mouseover(function() {
$('.NavGroup').hide();
$('#' + $(this).prop('id').replace('item','content')).show();
});
It's probably best to keep this timeout in a data property and clear it on mouseout.
$('.NavSelect h2').mouseenter(function () {
$(this).data('timeout', setTimeout(function () {
$('.NavGroup').hide();
$('#' + $(this).prop('id').replace('item','content')).show();
}, 1000));
}).mouseleave(function () {
clearTimeout($(this).data('timeout'));
alert('mouse left');
});
If I understand what you want to do, you need a setTimeout:
$('.NavSelect h2').mouseover(function() {
setTimeout(() => {
$('.NavGroup').hide();
$('#' + $(this).prop('id').replace('item','content')).show();
}, 1000);
});
Here, the documentation
Update
If you would clear the timeout on mouseleave I suggest you somethig like this:
let time = 0;
$('.NavSelect h2').mouseover(function() {
time = setTimeout(() => {
$('.NavGroup').hide();
$('#' + $(this).prop('id').replace('item','content')).show();
}, 1000);
}).mouseleave(() => { clearTimeout(time); });

Prevent jquery fadeIn many times

Need to prevent the emergence of tips several times (when not a single clue pointing at a link persists even if the cursor is not on a link).
$(function () {
$(".area_tooltip").mouseover(function () {
var tooltip = $("div#" + $(this).attr("id") + "");
tooltip.fadeIn();
}).mouseout(function () {
var tooltip = $("div#" + $(this).attr("id") + "");
tooltip.fadeOut();
});
});
To understand the problem to move the red square over several times, and then remove it in the direction
http://jsfiddle.net/8LnTC/1/
I apologize for my bad English
You need to stop any queued animations first...
$(function () {
$(".area_tooltip").mouseover(function () {
var tooltip = $("div#" + $(this).attr("id") + "");
tooltip.stop().fadeIn();
}).mouseout(function () {
var tooltip = $("div#" + $(this).attr("id") + "");
tooltip.stop().fadeOut();
});
});
Working jsfiddle example...
Incidentally, you shouldn't have multiple elements with the same ID. You need to rethink how you're going to relate the elements to each other - maybe use data attributes.
Here's a suggested alternative...
Working jsfiddle example...
HTML change
<a class="area_tooltip" data-associated-tooltip="item_1">show</a>
Javascript change
$(function () {
$(".area_tooltip").mouseover(function () {
var tooltip = $("div#" + $(this).data("associated-tooltip"));
tooltip.stop().fadeIn();
}).mouseout(function () {
var tooltip = $("div#" + $(this).data("associated-tooltip"));
tooltip.stop().fadeOut();
});
});
You put the tip's ID in the attribute data-associated-tooltip and then you can access that with $(this).data("associated-tooltip"). That will get rid of any ID conflicts which will most likely cause untold problems.

I couldn't stop setInterval in Jquery

Could you help me that, how can I stop this Interval when I mouseover #headline_image?
$("#headline li").live('mouseover', function() {
var HL = $(this).attr("data-name");
$("#headline_image").html("<img src='" + HL + "'>"); });
setInterval(function()
{ $('#headline li[data-id=' + count + ']').mouseover(); },4000); });
I tried as below in mouseover function; but it didnt work
clearInterval(function() { $('#headline li').mouseover(); });
you need to use the reference returned by setInterval to clear it
var interval = setInterval(function () {
$('#headline li[data-id=' + count + ']').mouseover();
}, 4000);
then
clearInterval(interval)
also make sure the declare the variable interval in a scope shared by both these pieces of code
You have to save the actual timerid from the setInterval() call and you pass that to clearInterval().
$("#headline li").live('mouseover', function() {
var HL = $(this).attr("data-name");
$("#headline_image").html("<img src='" + HL + "'>");
clearInterval(timerId);
});
var timerId = setInterval(function() {
$('#headline li[data-id=' + count + ']').mouseover(); },4000);
});
FYI, .live() has been deprecated since version 1.7 of jQuery and even removed from the latest versions of jQuery so you should be using .on() in the version 1.8 you are using.
If #headline is a static object (present initially and not recreated), then you could switch to .on() like this:
$("#headline").on('mouseover', "li", function() {
var HL = $(this).attr("data-name");
$("#headline_image").html("<img src='" + HL + "'>");
clearInterval(timerId);
});
var timerId = setInterval(function() {
$('#headline li[data-id=' + count + ']').mouseover(); },4000);
});
If #headline itself is dynamic, then change to:
$(static parent).on('mouseover', "#headline li", function() {
where you you replace static parent with a selector to the closest parent to #headline that is itself not dynamic.
For references on using .on() for dynamic elements see these references:
jQuery .on does not work but .live does
Does jQuery.on() work for elements that are added after the event handler is created?
Proper use of .on method in Jquery

Object screenoff in "onmouseover"

The code below shows a window when mouse is over a link. I wonder how to make this window appear on top of the word when it doesn't "fit" on the screen.
function showLayer(obj){
var div = document.getElementById(obj).style;
div.display = "block";
}
if i understand your question, here is some jquery to help (also replaces showLayer())
$(document).on("mouseenter", '#myElement', function () {
$("#" + obj).toggle();
});
$(document).on("mouseout", '#myElement', function () {
$("#" + obj).toggle();
});
$(document).on("mousemove", '#myElement', function (i) {
$("#" + obj).offset(function () {
return {left: i.pageX, top: i.pageY}
});
});
im not sure how you get the value for obj, so you would have to edit to your specific needs.

How do I change images every 6 seconds? [duplicate]

This question already has an answer here:
How can I execute javascript code every a specific time interval?
(1 answer)
Closed 9 years ago.
How do I add an interval to the below code so it does it change images automatically every 6 seconds?
I use this code from fearlessflyer.com
$(window).load(function () {
var theImage = $('ul li img');
var theWidth = theImage.width();
//wrap into mother div
$('ul').wrap('<div id="mother" />');
//assign height width and overflow hidden to mother
$('#mother').css({
width: function () {
return theWidth;
},
height: function () {
return theImage.height();
},
position: 'relative',
overflow: 'hidden'
});
//get total of image sizes and set as width for ul
var totalWidth = theImage.length * theWidth;
$('ul').css({
width: function () {
return totalWidth;
}
});
$(theImage).each(function (intIndex) {
$(this).nextAll('a')
.bind("click", function () {
if ($(this).is(".next")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex + 1) * theWidth)
}, 1000)
} else if ($(this).is(".previous")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex - 1) * theWidth)
}, 1000)
} else if ($(this).is(".startover")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (0)
}, 1000)
}
}); //close .bind()
}); //close .each()
}); //doc ready
Here is an extended answer
var intNum = 6000; //repeat every 6 seconds
function startInterval(){
window.int = setInterval(function(){
//code to move to next image
},intNum);
}
That will set the interval for the image, going to the next automatically, small adjustments might be needed when comparing to your click event for the switch, so I left the inside blank.
the function startInterval() should be called when you know that the rest of the code is loaded and ready (click events are set, ect).
When you do a click event to manually switch back and forth you want to use the following
clearInterval(int);
//code to switch image from click
startInterval();
You need to use the setInterval() function.
Basically, it would look something like:
var currentImg=0;//Current image tracker
var imgList["img1.jpg","img2.jpg","img3.jpg"];//Image names
var changeImage = function(){
//Change src attribute on img element
$('ul li img').attr('src','/imgdir/'+imgList[currentImg]);
if(currentImg>=imgList.length-1)//Check if current image is the last in the list
currentImg=0;//Sets to first images if true
else
currentImg++;//Sets to next image if false
}
//Sets an interval of 6000ms on the window object that calls the function changeImage()
//on every trigger
window.setInterval(changeImage(),6000);
MDN Reference
Hope this helps, I'd suggest checking out the jQuery Documentation aswell...
Use the setInterval() javascript function, as explained here.

Categories

Resources