jquery images active/inactive loading - javascript

Here is my code
$(function(){
var $list = $('.my-loading-list'),
$imgs = $list.find('img'),
animateImages = function(){
var active = 0;
setInterval(function(){
active = $list.find('img.active').index();
if(active > $imgs.length){
active = 0;
} else {
active++;
}
$imgs.attr('src', 'https://cdn3.iconfinder.com/data/icons/cool-me-down-thermometers/70/Weather_cloudy_grey-128.png');
$imgs.eq(active).addClass('active').attr('src', 'https://cdn3.iconfinder.com/data/icons/vibrant-weather/70/Colour_Weather_cloudy_grey-128.png');
}, 300);
setInterval(function(){
$imgs.removeClass('active');
}, 600);
};
animateImages();
});
And here is the snippet:
https://jsfiddle.net/8d4xfjgt/
I need to animate the third image as well. one and two are changing their source but not the third one.
Please suggest.

Do you want to change the 3 images, one by one like this, or all at the same time?
The problem is this value isn't updating correctly active = $list.find('img.active').index(). It's taking values -1,0 alternatively
$(function(){
var $list = $('.my-loading-list'),
$imgs = $list.find('img'),
animateImages = function(){
var active = 0;
setInterval(function(){
if(active > $imgs.length){
active = 0;
} else {
active++;
}
$imgs.attr('src', 'https://cdn3.iconfinder.com/data/icons/cool-me-down-thermometers/70/Weather_cloudy_grey-128.png');
$imgs.eq(active).addClass('active').attr('src', 'https://cdn3.iconfinder.com/data/icons/vibrant-weather/70/Colour_Weather_cloudy_grey-128.png');
}, 150);
setInterval(function(){
$imgs.removeClass('active');
}, 150);
};
animateImages();
});

Related

Having trouble with using one variable with 4 seperate ID's in jQuery

I want my code to run the click variable separately for each time a new ID is being clicked on:
var click = 0;
$("#head, #mouth, #nose, #eyes").click(function () {
if (click < 9) {
$(this).animate({left: "-=367px"}, 500);
click++;
} else {
$(this).animate({left: "0px"}, 500);
click = 0;
}
});
At the moment, every time an ID is clicked, that same click variable increments by 1 no matter which ID is being clicked. Wasn't sure on how to code this part without having to make 4 separate functions that do the same thing (wanted to reduce code redundancy).
You could identify the id of the target and then access an object based on that ID to get the click:
const clicks = {};
$("#head, #mouth, #nose, #eyes").click(function () {
const { id } = this;
const clickCount = clicks[id] || 0;
if (clickCount < 9) {
$(this).animate({left: "-=367px"}, 500);
clicks[id] = clickCount + 1;
} else {
$(this).animate({left: "0px"}, 500);
clicks[id] = 0;
}
});
You have 4 elements, so you will need 4 variables. Or you can have an array/object with 4 items/properties. I like using an object for this rather than an array because you can use the elements' IDs as the keys of the object:
var clicks = {};
$("#head, #mouth, #nose, #eyes").click(function() {
var id = this.id;
clicks[id] = clicks[id] || 0;
if (clicks[id] < 9) {
$(this).animate({left: "-=367px"}, 500);
clicks[id]++;
} else {
$(this).animate({left: "0px"}, 500);
clicks[id] = 0;
}
});

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

Previous and Next functions for js slider

I have almost finished this slider, but I don't know how to implement the functionality for next() and prev(). How can I implement these functions?
http://jsfiddle.net/M4t4L/11/
$(function () {
var container = $("#scene"),
i = 0,
count = container.find("li").length,
j = container.find("li").length - 1,
isAnimating = false;
container.find("li:first").css({
"width": "100%"
});
$("#trigger").click(function (e) {
if (!isAnimating) {
isAnimating = true;
e.preventDefault(e);
i++; if (i >= count) { i = 0; }
j++; if (j >= count) { j = 0; }
container.find("li")
.finish()
.removeClass('active')
.last()
.width(0)
.addClass("active")
.animate({
"width": "100%"
}, 800,
function () {
container.find("li").first().appendTo(container);
isAnimating = false;
});
}
});
});
The problem is that when I implement these functions and press the next or prev. Displays the last slide on one second, and then switches to the desired
http://jsfiddle.net/M4t4L/9
If you want to get a Next or Prev function running, you want to take control of the number of the slider where you are. I'm afraid you will have to play around with your i/j and make the position go in both directions.
Right now you count up your i and j, where you might want to go is to have a position var and an array of slider objects, then the click only would have to call for the next/prev object to be loaded and the animation can begin.
Something like this maybe..
var pos = 0;
var container = $('#scene').find('li');
$('.back').click(function() {
pos = pos - 1;
moveIt(pos);
});
$('.forth').click(function() {
pos = pos +1;
moveIt(pos);
});
function moveIt(pos) {
container[pos]... // Your animation goes here
}

Looping code when hovering with set delay in JavaScript with jQuery

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

Categories