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().
Related
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
}
I wanted to get rid of a slider-plugin, so i tried to build my own,
everything works nice but i´m stuck to stop the whole thing on hover and restart it again on mouseleave,
here is my js :
function startPslider(val) {
if (!val) {
val = 0;
}
var holder = 'slideHolder';
var text = 'slideText';
startInterval(holder, text, val);
}
function startInterval(holder, text, val) {
var t;
var i = val;
if (i > 2) {
i = 0
}
$('#' + holder + i).animate({
opacity: 1,
}, function () {
$(this).addClass('active')
$('.' + text + i).animate({
opacity: 1,
left: 0
}, 1200);
t = setTimeout(function () {
$('.' + text + i).animate({
opacity: 0,
left: '-400px'
}, 1200);
$('#' + holder + i).animate({
opacity: 0,
}, 2200).removeClass('active');
startPslider(i + 1);
}, 4000)
});
// Here´s the not working hover-function
$('#hpCanvas').hover(function () {
clearTimeout(t);
}, function () {
var id = $('.active').attr('id');
var slide = id.substring(11, 22);
console.log(slide)
startPslider(slide);
});
}
$(function () {
startPslider();
});
tryed to solve this with adding class 'active' to the current holder and at hover-out try to catch the current-slide number (val) and restart it again, starting on the correct slide, but it´s not working as I wish,
have a look at this fiddle, http://jsfiddle.net/zDh76/ you will find html and css there, as you see everything works fine as long you do not hover.
Maybe anyone has a helping hint how to stop the animation, clear the timer and go on with the correct slide on mouseleave?
UPDATE
i separated start and end-interval
function startPslider(i) {
if(!i){
i=0;
}
if(i >2){
i=0
}
console.log('started Slider with slide:'+i)
var holder = 'slideHolder';
var text = 'slideText';
startInterval(holder, text, i);
}
function startInterval(holder,text,i) {
var t;
var v;
console.log('started Interval with slide:'+i);
$('#'+holder+i).animate({
opacity:1,
}, function(){
$('.'+text+i).animate({
opacity:1,
left:0
},1200);
t= setTimeout(function(){endInterval(holder,text,i); },4000);
});
}
function endInterval(holder,text,i,cont){
console.log('end Interval with slide:'+i);
$('.'+text+i).animate({
opacity:0,
left:'-400px'
},1200);
$('#'+holder+i).animate({
opacity:0,
},2200, function(){
$('.slideHolder').css('opacity',0);
i = i+1;
startPslider(i);
});
}
I found it out myself,
i needed to unbind the hover event on #hpCanvas inside the mouseleave function like
$('#hpCanvas').hover(function(){
$('.slideHolder, .slideText').stop(true,true);
clearTimeout(t)
},function(){
endInterval(holder,text,i);
$('#hpCanvas').unbind('mouseenter mouseleave')
})
as the next call to bind it with hover event is inside the mouseleave-part of the first hover event.
thanks anyway for everyone reading this
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);
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
I have an array set with the heights of each hidden div, but when I use it, the div instantly jumps down, rather than slowly sliding as when there is a literal number.
EDIT: testing seems to reveal that it's a problem with the push method, as content_height.push(item.getElement('.moreInfo').offsetHeight);alert(content_height[i]);gives undefined, but alert(item.getElement('.moreInfo').offsetHeight); gives the correct values
Javascript:
window.addEvent('domready', function(){
var content_height = [];i=0;
$$( '.bio_accordion' ).each(function(item){
i++;
content_height.push( item.getElement('.moreInfo').offsetHeight);
var thisSlider = new Fx.Slide( item.getElement( '.moreInfo' ), { mode: 'horizontal' } );
thisSlider.hide();
item.getElement('.moreInfo').set('tween').tween('height', '0px');
var morph = new Fx.Morph(item.getElement( '.divToggle' ));
var selected = 0;
item.getElement( '.divToggle' ).addEvents({
'mouseenter': function(){
if(!selected) this.morph('.div_highlight');
},
'mouseleave': function(){
if(!selected) {
this.morph('.divToggle');
}
},
'click': function(){
if (!selected){
if (this.getElement('.symbol').innerHTML == '+')
this.getElement('.symbol').innerHTML = '-';
else
this.getElement('.symbol').innerHTML = '+';
item.getElement('.moreInfo').set('tween', {
duration: 1500,
transition: Fx.Transitions.Bounce.easeOut
}).tween('height', content_height[i]); //replacing this with '650' keeps it smooth
selected = 1;
thisSlider.slideIn();
}
else{
if (this.getElement('.symbol').innerHTML == '+')
this.getElement('.symbol').innerHTML = '-';
else
this.getElement('.symbol').innerHTML = '+';
thisSlider.slideOut();
item.getElement('.moreInfo').set('tween', {
duration: 1000,
transition: Fx.Transitions.Bounce.easeOut
}).tween('height', '0px');
selected = 0;
}
}
});
} );
});
Why could this be? Thanks so much!
There's nothing wrong with your code. The push method works as expected - here's an example: http://jsfiddle.net/oskar/D2xps/
You need content_height[i - 1].
Also I'd recomend you use another indexing (since your code using global variable 'i' and it could fail because of closures):
$$( '.bio_accordion' ).each(function(item, index) {
content_height[index] = item.getElement('.moreInfo').offsetHeight;
....
tween('height', content_height[index]);
});