Reputation: 84
I am just starting with jQuery, so be patient. How do I stop this blinking function on attempted window scroll or mouseenter? Thanks in advance!
http://jsfiddle.net/e2s8besv/1/
<p>blink me<p>
<style>p {display:none;}</style>
<script>
(function( $ ) {
$.fn.blink= function(speed) {
$(this).fadeIn(speed).fadeOut(speed).blink(speed);
};
}( jQuery));
$("p").blink(1500);
</script>
Upvotes: 0
Views: 212
Reputation: 75083
I would most likely do this, if you're learning jQuery and assuming, javascript as well...
HTML
<p class="hide blink">blink me<p>
Script
$(function() {
objInt = setInterval(function() {
$(".blink")
.fadeTo('fast', 0.2)
.fadeTo('fast', 0.5);
}, interval);
// stop on scroll (only works if there's actualy a scroll area)
$( window ).scroll(function() {
clearInterval(objInt);
});
// stop on mouseenter the paragraph tag
$( ".blink" ).mouseenter(function() {
clearInterval(objInt);
});
});
var interval = 500, objInt;
live version in JsBin: http://jsbin.com/gajafokale/1/edit?html,js,output
Upvotes: 1
Reputation: 12132
I would use a boolean
flag to check if the action is happening. I would also try to separate the code in functions so that you can reuse them later if needed. Try doing something like this:
HTML:
<p style="display:none">BLINK</p>
<button>STOP</button>
JS:
var blinking = false;
function blink(speed) {
if (blinking) {
$("p").fadeIn(speed, function() {
$(this).fadeOut(speed);
blink(speed);
});
}
}
function startBlink(speed) {
blinking = true;
blink(speed);
}
function stopBlink() {
blinking = false;
}
$(document).ready(function(){//makes sure your code runs once the DOM has completely loaded.
startBlink(1500);
$('button').click(stopBlink);
});
Upvotes: 1
Reputation: 1984
I would suggest something with boolean variable and without recursion (would be more CPU-friendly):
<p>blink me<p>
<style>p {display:none;}</style>
<button>Stop Blinking!</button>
<script>
var isBlinkEnabled=true;
(function( $ ) {
$.fn.blink= function(speed) {
while(isBlinkEnabled)
{
$(this).fadeIn(speed).fadeOut(speed);
}
};
}( jQuery));
$("p").blink(1500);
$("button").click(function(){
isBlinkingEnabled=false;
})
</script>
Upvotes: -1