Looping code when hovering with set delay in JavaScript with jQuery - javascript

I'm looking to start and stop a loop with a set delay with a jQuery hover event. I've been trying to do it with "mouseover" and "mouseout" with no luck.
Example (odd psudocode):
Mouseover
Loop
Change text colour
Wait 100ms
Mouseout
Stop loop
I'm sure this is super easy, I just don't quite know how to structure it with JavaScript.
Thanks in advance.

This might work:
$(function(){
$('#test').hover(function(){
var self = $(this),
rnd = null,
col = null;
this.iid = setInterval(function(){
col = ['#'];
rnd = ~~(Math.random()*255);
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
self.css({backgroundColor: col.join('')});
}, 100);
}, function(){
if(this.iid){
clearInterval(this.iid);
delete this.iid;
}
});
});​
See this in action: http://www.jsfiddle.net/YjC6y/19/

function rgb() {
var color = 'rgb(';
for (var i = 0; i < 3; i++) {
color += Math.floor(Math.random() * 255) + ',';
}
return color.replace(/\,$/, ')')
}
var loop = null;
$(function () {
$('#someid').hover(function () {
var $this = $(this);
loop = setInterval(function () {
$this.css({backgroundColor: rgb() });
}, 100);
}, function () {
clearInterval(loop);
});
});
try an example : http://jsbin.com/uraxe4

$("#yourElem").hover(
function () { /* mousenter */
$this = $(this);
// take note that the mouse is currently hovering
$this.data("isHovering", true);
// create an interval and store its ID in jQuery data
$this.data("loopId", setInterval(function () {
// only do something if we are still hovering
if ($this.data("isHovering")) {
$this.css("color", getRandomColorValue());
}
}, 100);
},
function () { /* mouseleave */
$this = $(this);
// take note that the mouse is no longer hovering
$this.data("isHovering", false);
// clear the interval that was set and delete the ID
if ($this.data("loopId")) {
clearInterval($this.data("loopId"));
$this.data("loopId", false);
}
}
)

changeColorTimerId = -1;
$('.box').hover(function(){
//mouseOver code here
changeColorTimerId = setInterval ( changeColor, 1000 );
},function(){
//mouseOut code here
if ( changeColorTimerId ){
clearInterval ( changeColorTimerId )
}
});
function changeColor(){
$(".box").css ( 'backgroundColor', '' + getRandomColor() );
}
function getRandomColor(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
working example here:
http://jsbin.com/etogi3/2

Related

How to animate the HTML contents using jquery..

I have an HTMl texts that is getting changed dynamically.Now as per my requirement i have to display them in animated form like fading and in some motion but i am not aware of this ..
Here is my Code..
<script type="text/javascript">
var v = {};
v[0] = "Your Text<br/>Hello";
v[1] = "Your Text2<br/>Hello2";
v[2] = "Your Text3<br/>Hello3";
var i = 0;
window.setInterval(function () {
$("#dynamicMessage").html(v[i]);
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
}, 10000);
</script>
Please have a look and let me know how can i animate my text contents in HTML..
Thanks..
You could use a combination of fadeOut() and fadeIn()
$("#dynamicMessage").fadeOut( "slow", function() {
$("#dynamicMessage").html(v[i]).fadeIn('slow');
})
Check this demo - http://jsfiddle.net/xw2j6hsp/1/
UPDATE
Saw this comment, on #laruiss answer:
"If there are other way by which i can show the text popping from the
left"
Thought i'd code this up for you. Just add in some animation. check it - http://jsfiddle.net/m6bnq1ja/
There's no animating the content change. What you can do is hide the element, change its content, then fade it in, something like below. It'll probably look the same to the user.
$("#dynamicMessage").hide().html(v[i]).fadeIn();
or
$("#dynamicMessage").fadeOut(500, function() {
$(this).html(v[i]).fadeIn(500);
});
Don't forget to clearTimeout (or clearInterval)
var v = [
"Your Text<br/>Hello",
"Your Text2<br/>Hello2",
"Your Text3<br/>Hello3"
],
i = 0,
timeout = null,
change = function (text) {
var $dynamicMessage = $("#dynamicMessage")
.fadeOut("slow", function() {
$dynamicMessage.html(text).fadeIn();
});
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
timeout = window.setTimeout(function() {change(v[i]);}, 2000);
}
change(v[i]);
$(window).unload(function() {window.clearTimeout(timeout); timeout = null;});
JSFiddle
var v = {};
v[0] = "Your Text<br/>Hello";
v[1] = "Your Text2<br/>Hello2";
v[2] = "Your Text3<br/>Hello3";
var i = 0;
window.setInterval(function () {
$("#dynamicMessage").fadeToggle( "slow", function() {
$("#dynamicMessage").html(v[i]).fadeToggle('slow');
});
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
}, 4000);
Note : you can also use "fadeOut" & "fadeIn" in place of "fadeToggle"

Stop loop and fade in area that is hovered on

I have a bit of javascript/jquery I am trying to figure out. What I have already is three boxes that the content fades in and out and loops through the three and repeats. What I am trying to do is when "box x" is hovered over the loop fades out and stops never to start again, and the box that is hovered on, the content below the box fades in and stays... unless another box is hovered over, then the content that faded in from the other hovered box will fade out and the new box that was hovered on, the content that coincides with that box fades in and stays fade in, and so forth.
How would I go about doing this?
Here is a jsfiddle example: http://jsfiddle.net/q0htx0no/
javascript/jquery
var infoboxes = $(".count p");
var counter = 0;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000);
});
}
$(function() {
rotate();
});
Thanks for any help
One option would be to have a global variable (a 'flag') that would indicate if the rotation should be stopped. Once a box has been hovered over, it should set hovered to True and should fade in that specific box.
Yep, use a global variable. Something like this:
var infoboxes = $(".count p");
var counter = 0;
var goAhead = true;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
checkRotate();
})
}, 1000);
});
}
function checkRotate() {
if (goAhead) { rotate(); }
}
$('.about').on('mouseover', function() {
goAhead = false;
var index = $(this).index();
var boxesToClear = $(infoboxes).filter(function(i) { return i !== index; });
$(boxesToClear).fadeOut(1000, function() {
$(infoboxes[index]).fadeIn(1000);
});
});
checkRotate();
DEMO
Here's one way to do it. It can probably be improved.
http://jsfiddle.net/vbt67x0h/2/
var infoboxes = $(".count p");
var counter = 0;
var isrotating = false;
function rotate(){
isrotating = true;
$(infoboxes[counter]).fadeIn(1000).delay(1000).fadeOut(1000);
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
}
//immediately stop rotate and hide all
function stoprotate(){
clearInterval(tmrrotate);
isrotating = false;
for(var x=0;x<infoboxes.length;x++){
$(infoboxes[x]).stop();
$(infoboxes[x]).hide();
}
}
rotate();
//rotate every 3 seconds, 1 to fadein, 1 to pause, 1 to fadeout
var tmrrotate = setInterval(function() {
rotate();
}, 3000);
$(".about").on('mouseover', function() {
if(isrotating){stoprotate()}
$(infoboxes[$(this).index()]).fadeIn(1000);
})
.on('mouseleave', function() {
$(infoboxes[$(this).index()]).fadeOut(1000);
});
You should make a timed array:
var arTimer = [];
and push all timers into that array, clearTimeout on hover and show only hovered index:
var infoboxes = $(".count p");
var counter = 0;
var arTimer = [];
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
arTimer.push(setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000));
});
}
function cleararTimer(){
for (var i = 0; i < arTimer.length; i++) {
clearTimeout(arTimer[i]);
}
}
$(function() {
rotate();
$('.about').on('mouseover', function(){
cleararTimer();
var hovered = $(this).index();
$('.count p').not(':eq('+hovered+')').fadeOut(1000);
$('.count p:eq('+hovered+')').fadeIn(1000);
});
});
jsFiddle Example

showing descriptions with simple carousal using jquery

I am building a simple sliding carousal that shows an iphone with 3 screens. Each time you press the next or previous arrow, it slides to the new image. I have that part figured out, but I am having trouble displaying/hiding the text with each slide. Right now, all three text descriptions are showing.
$(function () {
var onSlide = 0;
var moveSlide = 0;
var imageWidth;
$('.iphone-overlay .nav-left')
.on('click', function () {
if (onSlide > -1) {
onSlide--;
doStuff();
};
})
$('.iphone-overlay .nav-right')
.on('click', function () {
if (onSlide < 1) {
onSlide++;
doStuff();
};
})
function doStuff() {
console.log(onSlide);
imageWidth = $('.banner-slider img').width();
moveSlide = (imageWidth / 3) * onSlide;
$('.banner-slider img').css('left', moveSlide);
}
});
Here is my jsfiddle: http://jsfiddle.net/WnQ7S/
Any help would be appreciated
I played with it a couple of hours and came up with this FIDDLE.
All of the text is hidden in a .holder.
Then when the different images are moved, the equivalent text is moved into a div below the picture.
The way the images were looped and counted had to be changed.
Here's the relevant JS
$(function () {
var onSlide = 0;
var moveSlide = 0;
var imageWidth;
$('.iphone-overlay .nav-left').on('click', function () {
onSlide = onSlide - 1;
if ( onSlide < 1 )
{
onSlide = 3;
}
doStuff();
});
$('.iphone-overlay .nav-right').on('click', function () {
onSlide = onSlide + 1;
if ( onSlide > 3 )
{
onSlide = 1;
}
doStuff();
});
function doStuff() {
console.log(onSlide);
imageWidth = $('.banner-slider img').width();
moveSlide = (imageWidth / 3) * onSlide;
$('.banner-slider img').css('left', moveSlide);
$('.putmehere').html('');
// alert(onSlide);
$('.putmehere').append( $('.holder .slide' + onSlide).html() );
}
});

'Pulsing' a border in Javascript/JQuery

I am in the process of applying validation on a web form -one of the things I would like to do is add a pulsing border to the div which contains the erroneous input.
This solution: border highlighting loop with jquery and http://jsfiddle.net/Ue4wy/4/ pretty much hits the mark.
But I want to be able to fade the yellow border to black on the click handler & reset the loop (this example pauses the loop), so the next time the user hits submit it starts again.
Reseting the colour to black works using the code below (though I am sure there is a more elegant solution), but how do I reset the loop?
$('#weight').animate({
borderBottomColor: '#000',
borderLeftColor: '#000',
borderRightColor: '#000',
borderTopColor : '#000'
}, 'fast' );
Any ideas appreciated!
I've updated the update() function to accept an argument, i, which is then called in the click handler, along with window.clearTimeout():
var addClickHandler = function() {
$("div").click(function() {
window.clearTimeout(timer);
update(0);
});
};
This does require that the other calls to update() also need to pass the i:
var update = function(i) {
$("div").css("border-color", 'rgb(' + i + ',' + i + ',' + 0 + ')');
};
JS Fiddle demo.
Edited to amend the click-handler to offer a toggle (stop/start) for the animation:
var addClickHandler = function() {
$("div").toggle(function() {
window.clearTimeout(timer);
update(0);
}, function() {
anim.go();
});
};
JS Fiddle demo.
Edited for a slightly more context-aware click-handler, this version checks for the existence of the timer variable and, if it isn't found, starts the animation. If it is found then it clears the timeout, sets the timer to false and calls update(0) to reset the borders to black:
var addClickHandler = function() {
$("div").click(function() {
console.log(timer);
if (!timer){
timer = window.setTimeout(anim.go, 30);
}
else {
window.clearTimeout(timer);
timer = false;
update(0);
}
});
JS Fiddle demo.
References:
toggle().
window.clearTimeout().
Here's a jQuery UI effect to pulsate the border:
$.effects.borderPulsate = function(o) {
return this.queue(function() {
var elem = $(this),
mode = $.effects.setMode(elem, o.options.mode || 'show'),
times = (o.options.times || 5),
duration = o.duration ? o.duration : $.fx.speeds._default,
isVisible = elem.is(':visible'),
color = (o.options.color || 'rgb(255,255,0)'),
startColor = (o.options.startColor || elem.css('border-color') || 'transparent');
if (!isVisible) {
elem.show();
}
if ((mode == 'hide' && isVisible) || (mode == 'show' && !isVisible)) {
times--;
}
for (var i = 0; i < times; i++) {
elem.animate({ 'border-color': color }, duration, o.options.easing, function() {
elem.css( 'border-color', startColor );
});
}
elem.animate({ 'border-color': color }, duration, o.options.easing, function() {
(o.callback && o.callback.apply(this, arguments));
});
elem
.queue('fx', function() { elem.dequeue(); })
.dequeue();
});
};
http://jsfiddle.net/cdeutsch/TjkNd/
You can change colors on all borders at the same time with borderColor, but you don't need to animate that. You could add a reset method to your object to take care of the whole thing:
var reset = function() {
i = 0;
step = 10;
up = true;
if(timer) window.clearTimeout(timer);
timer = null;
$('#weight').css('borderColor', '#000');
}
Then on your click handler, you call anim.reset() after anim.stop().

HTML flashing text colors

This is quite an unusual request, but..
Is there anyway to make some text alternate between 2 colors every second?
So it appears as though it's flashing between say... red and grey? I don't mean background color, I mean the actual font color. I'm assuming it would need javascript or something.
Is there any simple way to do that?
(disregarding the fact it could look ugly)
UPDATE
Id like to call to this function several times on my page, each one passing along a different color to alternate with GREY
.
As per your request:
function flashtext(ele,col) {
var tmpColCheck = document.getElementById( ele ).style.color;
if (tmpColCheck === 'silver') {
document.getElementById( ele ).style.color = col;
} else {
document.getElementById( ele ).style.color = 'silver';
}
}
setInterval(function() {
flashtext('flashingtext','red');
flashtext('flashingtext2','blue');
flashtext('flashingtext3','green');
}, 500 ); //set an interval timer up to repeat the function
JSFiddle here: http://jsfiddle.net/neuroflux/rXVUh/14/
Here's an easy way to do it with plain JavaScript:
function flash() {
var text = document.getElementById('foo');
text.style.color = (text.style.color=='red') ? 'green':'red';
}
var clr = setInterval(flash, 1000);
This will alternate the color of the text between red and green every second. jsFiddle example.
Here's another example where you can set the colors of different elements:
function flash(el, c1, c2) {
var text = document.getElementById(el);
text.style.color = (text.style.color == c2) ? c1 : c2;
}
var clr1 = setInterval(function() { flash('foo1', 'gray', 'red') }, 1000);
var clr2 = setInterval(function() { flash('foo2', 'gray', 'blue') }, 1000);
var clr3 = setInterval(function() { flash('foo3', 'gray', 'green') }, 1000);
and the jsFiddle to go with it. You pass the ID of the element you want to flash and the two colors to alternate between.
With JavaScript it is very simple:
function alternateColor(color, textId, myInterval) {
if(!myInterval){
myInterval = 1000;
}
var colors = ['grey', color];
var currentColor = 1;
document.getElementById(textId).style.color = colors[0];
setInterval(function() {
document.getElementById(textId).style.color = colors[currentColor];
if (currentColor < colors.length-1) {
++currentColor;
} else {
currentColor = 0;
}
}, myInterval);
}
alternateColor('red','myText');
Call the function with the first argument being a color, the second being your text's ID, and third being the interval time (optional). Jsfiddle example
Here's some simple easy to understand code.
var count_x = 1,
max_x = 5; // Change this for number of on-off flashes
var flash_color_notify = setInterval(function () {
/* Change the color depending if it's even(= gray) or odd(=red) */
if (count_x % 2 === 0) { // even
$('#element').css('color', 'gray');
} else { // odd
$('#element').css('color', 'red');
}
/* Clear the interval when completed blinking */
if (count_x === max_x * 2) {
clearInterval(flash_color_notify);
} else { count_x += 1; }
}, 500);

Categories