setInterval + image src changes when clicked on button - javascript

I want to give blink effect(dark and light) when clicked on the button.I have written the following code but it does not work.So please help me.
$(document).ready(function () {
$(".search").click(function () {
setInterval(function () {
var curSrc = $("#red").attr('src');
if (curSrc === '../images/lightred.jpg') {
$(curSrc).attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
$(curSrc).attr("src", "../images/lightred.jpg");
}
}, 2000);
});
});

curSrc is your source attribute, yet you are trying to wrap it in jQuery, that won't make it an object. You'll have to target #red again and then set the source:
if (curSrc === '../images/lightred.jpg') {
$("#red").attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
$("#red").attr("src", "../images/lightred.jpg");
}

It seems the question might be how to make the button blink. This can be done with the css background-color property. CSS is a better fit, assuming lightRed and darkRed are solid colors. If the images are required you can use the background-image property.
<input type="button" class="search lightRed" value="Search"/>
<style>
.lightRed { background-color: lightcoral }
.darkRed { background-color: darkRed }
</style>
<script>
$(document).ready(function(){
$(".search").click(function(){
setInterval(function(){
var isLightRed = $(".search").hasClass("lightRed");
if (isLightRed) {
$(".search").removeClass("lightRed").addClass("darkRed");
} else {
$(".search").removeClass("darkRed").addClass("lightRed");
}
},2000);
});
});
</script>

Related

How to Fade Out an element using Javascript

I have a loading page that I used javascript to make. I would like to be able to fade-out the loading page as the index.html fades in. I understand this can easily be done with jQuery, but would like to not use jQuery since I have yet to use it on this site. I understand this may be a common question, but I have not been able to tailor other answers to my solution since most use jQuery.
I am thinking to edit the opacity of the loading element onReady. Or could I do this with simple CSS?
Javascript:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
HTML:
<div id="loading">
<div class="logo">
Logo
</div>
<span class="loading-center-cross"></span>
<h3>Loading...</h3>
</div>
<div id="page">
.....
</div>
I expect for the loading screen to fade to the index.html as previously described. Thanks for all the help!
You can do this with CSS, using something like the following:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).classList.toggle('fade-in-out', value);
}
onReady(function () {
show('page', true);
show('loading', false);
});
And have the following CSS:
#page,
#loading {
transition: opacity 1s;
}
.fade-in-out {
opacity: 0;
pointer-events: none;
}
That way, the show() function will toggle a class of fade-in-out based on value, and there will be a transition to 'fade' the div in and out, with an addition of pointer-events: none to make the div non-interactive whist transitioning.

javascript delay popup

im having a prob with javascript which has been bugging me for hours now. I need to delay a css popup so that if you just scroll mouse around page you wont get loads of popups.
Whatever i try it either makes the popup act goofy, poping up after x seconds with a swipe of any link, auto closing etc etc. if i add a timer to the mouseover it starts acting weird, if i then delete the timer for mouseout it works fine but you can no longer mouseover menu before it closes, also tried adding negative margin and it autocloses
cheers all
javscript
<script type="text/javascript">
var span = document.querySelectorAll('.pop');
for (var i = span.length; i--;) {
(function () {
var t;
span[i].onmouseover = function () {
hideAll();
clearTimeout(t);
this.className = 'popHover';
};
span[i].onmouseout = function () {
var self = this;
t = setTimeout(function () {
self.className = 'pop';
}, 300);
};
})();
}
function hideAll() {
for (var i = span.length; i--;) {
span[i].className = 'pop';
}
};
</script>
css
.pop {
position:relative;
}
.pop div {
display: none;
}
.popHover {
position:absolute;
}
.popHover div {
background-color:#FFFFFF;
border-color:#AAAAAA;
border-style:solid;
border-width:1px 2px 2px 1px;
color:#333333;
padding:5px;
position:absolute;
z-Index:9999;
width:150px;
display: inline-block;
margin-top: -20px;
}
Using jquery might be a little more helpful for what you are trying to do. Try something like this:
// Use a CDN to take advantage of caching
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var t;
$('.pop').on('mouseover', $.proxy(function () {
hideAll();
clearTimeout(t);
this.addClass('popHover');
this.removeClass('pop');
}, this));
$('.pop').on('mouseout', $.proxy(function () {
var self = this;
t = setTimeout(function () {
self.addClass('pop');
self.removeClass('popHover');
}, 300);
},this));
function hideAll() {
// Since you are calling this from the mouseover function of all the
// elements with the 'pop' class, I dont understand what the purpose of this class
// is so it might not be entirely correct.
$('.pop').addClass('pop');
}
</script>
Let me know if this helps. If you still need it. It would be helpful to have a fiddle to maybe tweak to give you a more accurate response.

Button hiding not functioning properly

HTML Code:
<div id="slick-slidetoggle">wxyz</div>
<div id="slickbox" >abcd</div>​
JavaScript:
var hoverVariable=false;
var hoverVariable2=false;
$('#slickbox').hide();
$('#slick-slidetoggle').mouseover(function() {
hoverVariable2=true;
$('#slickbox').slideToggle(600);
return false;
})
$('#slick-slidetoggle').mouseleave(function() {
hoverVariable2=false;
setTimeout(function (){
if(!hoverVariable && !hoverVariable2){
$('#slickbox').slideToggle(600);
return false;}
}, 1000);
})
$('#slickbox').mouseleave(function() {
hoverVariable=false;
setTimeout(function (){
if(!hoverVariable && !hoverVariable2){
$('#slickbox').slideToggle(600);
return false;}
return false;
}, 1000);
})
$('#slickbox').mouseover(function() {
hoverVariable2=false;
hoverVariable=true;
})​
CSS Code:
#slickbox {
background: black;
width:100px;
height: 135px;
display: none;
cursor:pointer;
color:white;
}
#slick-slidetoggle{
background: yellow;
width:100px;
height: 135px;
cursor:pointer;
color:black;
}
​
Now the desired behaviour is that when mouse is slide over yellow div("wxyz") black div("abcd") should slide down and if mouse is moved out of yellow without moving on to black div, the black div should hide after two seconds.
This is happening. If mouse is moved over black div immediately after moving out of yellow div the black div should not hide as long as the mouse is on the black div. This is also happening.
Next steps are bit difficult to explain but I'll try, when mouse is moved over yellow div and black div comes out then mouse is moved over black div and within two seconds if it moved out of it(black div) then the whole animation goes haywire. Its behaviour is reversed. But if the mouse is kept on black div for more than two seconds and then it is moved out then the whole script runs fine.
This is the link to explain better. http://jsfiddle.net/HAQyK/381/
Try replacing slideToggle() with the appropriate slideUp() and slideDown() calls. http://jsfiddle.net/tppiotrowski/HAQyK/386/
var hoverVariable = false;
var hoverVariable2 = false;
$('#slickbox').hide();
$('#slick-slidetoggle').mouseover(function() {
hoverVariable2 = true;
$('#slickbox').slideDown(600);
return false;
})
$('#slick-slidetoggle').mouseleave(function() {
hoverVariable2 = false;
setTimeout(function() {
if (!hoverVariable && !hoverVariable2) {
$('#slickbox').slideUp(600);
return false;
}
}, 1000);
})
$('#slickbox').mouseleave(function() {
hoverVariable = false;
setTimeout(function() {
if (!hoverVariable && !hoverVariable2) {
$('#slickbox').slideUp(600);
return false;
}
return false;
}, 1000);
})
$('#slickbox').mouseover(function() {
hoverVariable2 = false;
hoverVariable = true;
})​
I re-coded a solution. Checkout the fiddle here
var hideB;
var $black = $('#slickbox');
var $yellow = $('#slick-slidetoggle');
function showBlack() {
if( hideB ) window.clearTimeout( hideB );
$black.stop( true, true );
$black.slideDown(600);
}
function hideBlack() {
hideB = setTimeout( function( ) {
$black.stop( true, true );
$black.slideUp( 600 ); }
, 1000 );
}
$black.hide();
$yellow.mouseenter(function() {
showBlack();
})
$yellow.mouseleave(function() {
hideBlack();
});
$black.mouseleave( function( ) {
hideBlack();
});
$black.mouseenter( function( ) {
showBlack();
});
Your problem seems to be that the slideToggle in firing twice in quick succession because of your duplicate timeout functions. The cleanest way to deal with timeouts or intervals is to store them in a variable to give you the control of removing them when not needed:
// Defined in global scope
var timer;
$('#slick-slidetoggle').mouseleave(function() {
hoverVariable2=false;
// Timer set as function
timer = setTimeout(function (){
if(!hoverVariable && !hoverVariable2){
$('#slickbox').slideToggle(600);
// Timer no longer need and so cleared
clearTimeout(timer);
return false;}
}, 1000);
});
EDIT: Neglected to add the slideUp/slideDown instead of Toggle as per the correct answer above. See the updated jsFiddle which is now correct: http://jsfiddle.net/HAQyK/390/
Another way you could approach your script is to use jQuerys delay funciton and the stop(); method for animation. Wrap the divs in a container and you've got a much simpler block of code:
$('#slick-container').mouseenter(function() {
$('#slickbox').stop().slideDown(600);
}).mouseleave(function(){
$('#slickbox').stop().delay(1000).slideUp(600);
});
Check it out here: http://jsfiddle.net/HAQyK/387/

Add fade effect to jQuery image replace on hover script

There were a few topics about this already but they didn't quite help in my case. I've written a small script to change the image source of some social icons when hovered over. I'm trying to add a fadeIn and fadeOut effect so it isn't just a straight up image swap. Here is my script:
$(".social_icons").live('hover', function() {
if ($(this).attr("class") == "social_icons") {
this.src = this.src.replace("-black","-color");
} else {
this.src = this.src.replace("-color","-black");
}
$(this).toggleClass("on");
});
How can I add a fadeIn/fadeOut effect to this?
Try this
$(".social_icons").live('hover', function() {
var $curr = $(this);
if ($(this).attr("class") == "social_icons") {
$curr.fadeOut('slow', function () {
$curr.attr('src', this.src.replace("-black","-color"));
$curr.fadeIn('slow');
});
} else {
$curr.fadeOut('slow', function () {
$curr.attr('src', this.src.replace("-color","-black"));
$curr.fadeIn('slow');
});
}
$(this).toggleClass("on");
});

How do I clear this setInterval inside a function?

Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an anonymous function:
function intervalTrigger() {
setInterval(function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000);
};
intervalTrigger();
How do I clear this? I gave it a shot and tried var test = intervalTrigger(); clearInterval(test); to be sure, but that didn’t work.
Basically, I need this to stop triggering once my Google Map is clicked, e.g.
google.maps.event.addListener(map, "click", function() {
//stop timer
});
The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
the_int=window.clearInterval(the_int);
Simplest way I could think of: add a class.
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause/unpause</button></p>

Categories