Show Div on Mouseover after three second - javascript

I want on first click it will show after 3 seconds but after the first click when I clicked it will shown before 3 seconds:
function Func1()
{
document.getElementById('div1').style.visibility = "visible" ;
}
function Func1Delay()
{
setTimeout("Func1()", 3000);
}
function Func2Delay()
{
document.getElementById('div1').style.visibility = "hidden" ;
}

Your English or description is very poor, but from what I understand, you want something like this :
var div = document.getElementById('div1'),t;
function changeStyle(element,prop,value){
element.style[prop] = value;
}
function showDiv(){
changeStyle(div,'opacity','1');
}
function hideDiv(){
changeStyle(div,'opacity','0');
}
div.addEventListener('mouseover',function(){
t = setTimeout(showDiv,3000);
},false);
div.addEventListener('mouseout',function(){
clearTimeout(t);
hideDiv();
},false);​
Here's a demo : http://jsfiddle.net/gion_13/TSVA5/
You have to hover the "invisible" div and it will show after 3 seconds.

this works for me
the markup:
<input type="button" value="clickme" onmouseout="ClearIntv()" onmouseover="DelayShow('showMe',5000)" />
<div id="showMe" style="display:none;background-color:red;width:50px;height:50px;">
</div>
the script:
var intv;
function DelayShow(timeOutMs) {
var elm = document.getElementById("showMe");
var now = new Date().getTime();
var end = now + timeOutMs;;
intv = setInterval(function () {
now = new Date().getTime();
if (now >= end) {
elm.style.display = "block";
clearInterval(intv);
}
}, 500);
}
function ClearIntv() {
clearInterval(intv);
}
Activates the counter on MouseOver, and cancels on MouseOut

Related

jQuery SetTimeout for Show / Hide div does not work

I am writing a jQuery which is supposed show/hide a series of images after an image is clicked. It basically, hides the current image and shows the next one when onClick event.
The function I have written so far works except one feature: On image 3, I want to set a timer and then switch to image 4, even if the user hasn't click it.
I am using a setTimeout and the timeout triggers except that it does not switch to next image.
This is my function:
(function($) {
$(document).ready(function () {
var count = 0;
$('.squirrel').click(function () {
$(this).hide();
var next = $(this).next();
if (next.length == 0){
next = $(this).parent().find('.squirrel').first();
count = -1;
}
next.show();
if (count == 1) {
setTimeout(
function() {
alert("Should switch to 4 now but it doesn't work");
$(this).hide();
var next = $(this).next();
next.show();
count++;
}, 2000
);
} else {
count++;
}
});
});
})(jQuery);
This is the HTML:
<div id="squirrelContainer">
<img src="1.png" class="squirrel default">
<img src="2.png" class="squirrel">
<img src="3.png" class="squirrel" id = "3">
<img src="4.png" class="squirrel">
</div>
Here's a JSFiddle.
Because you are using the same image not the next one.
(function($) {
$(document).ready(function () {
var count = 0;
$('.squirrel').click(function ()
{
$(this).hide();
var next = $(this).next();
if (next.length == 0)
{
next = $(this).parent().find('.squirrel').first();
count = -1;
}
next.show();
if (count == 1)
{
let that = $(this).next();
setTimeout(
function()
{
console.log("Should switch to 4 now but it doesn't work");
that.hide();
var next = that.next();
next.show();
count++;
}, 2000
);
}
else
{
count++;
}
});
});
})(jQuery);
https://jsfiddle.net/dyt9opLz/

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

How to stop and resume an interval instead of clearing and recall it?

I got this interval function which adds + 1 every second to this element, and a button which stops it with clearInterval(), but i want to "stop" and "resume" the interval instead of "clear" and restarting it. For example if the interval was stopped with 700 miliseconds, so i want to resume it for runnig from these 700 miliseconds and not from 0.
How can i do that?.
var testingB = $('#testing');
var testingBox = $('.text3');
var counter = 0;
var checker = null;
setInterval( function () { testingBox.text(counter); },1);
var id = setInterval( function () { counter++; },1000);
function adder() {
if (checker === null ) {
clearInterval (id);
checker = true;
testingB.text('Keep Counting');
}
else {
id = setInterval( function () { counter++; },1000);
checker = null;
testingB.text('Stop Couting');
};
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="testing" onclick="adder()"> Stop Counting </button>
<p class="text3"> </p>

Restart function when done in Javascript

I'm trying to get this to restart when done, or every 6 seconds:
window.onload = function() {
document.getElementById('slide1').style.display = "none";
document.getElementById('slide1').style.display = "block";
setTimeout(function(){
document.getElementById('slide1').style.display = "none";
document.getElementById('slide2').style.display = "block";
setTimeout(function(){
document.getElementById('slide2').style.display = "none";
document.getElementById('slide3').style.display = "block";
}, 1000);
}, 1000);
}
I've tried the other questions in Stack Overflow, but they don't work.
Thanks in advance.
You mean this?
// run every end of process:
var loader = function() {
setTimeout(function(){
document.getElementById('slide1').style.display = "none";
document.getElementById('slide2').style.display = "block";
setTimeout(function(){
document.getElementById('slide2').style.display = "none";
document.getElementById('slide3').style.display = "block";
loader();
}, 1000);
}, 1000);
};
window.onload = function() {
document.getElementById('slide1').style.display = "none";
document.getElementById('slide2').style.display = "block";
loader();
};
// Or you can run every 6 seconds
var loader = function() {
setTimeout(function(){
document.getElementById('slide1').style.display = "none";
document.getElementById('slide2').style.display = "block";
setTimeout(function(){
document.getElementById('slide2').style.display = "none";
document.getElementById('slide3').style.display = "block";
loader();
}, 1000);
}, 1000);
};
window.onload = function() {
document.getElementById('slide1').style.display = "none";
document.getElementById('slide2').style.display = "block";
//initial run
loader();
//run every 6 seconds
setInterval(loader, 6000);
};
This should do.
The original code was going through elements slide1 to slide6, every second it will hide the last one and show the new one, ex: hide slide1-show slide2, hide slide2-show slide3, etc....
This code replaces the setTimeout with setInterval, which then checks an index var to hide the latest shown one and shown the next one and then increments the index.
var index=1;
window.onload = function() {
document.getElementById('slide1').style.display = "block";
setInterval(function(){
if(index==6)
index=1;
document.getElementById('slide'+index).style.display = "none";
document.getElementById('slide' + (index+1)).style.display = "block";
index = index+1;
}, 1000);
}
To answer your main question on "how to restart?", in this example you could make use of the modulus operator (%).
In addition, rather than using querySelector each time the timer fires, try saving the HTML elements in variables.
Below is an example with 5 hard-coded slides, or, slide elements.
// initialize variables
var slideElements = [];
slideElements.push(document.getElementById("slide1"));
slideElements.push(document.getElementById("slide2"));
slideElements.push(document.getElementById("slide3"));
slideElements.push(document.getElementById("slide4"));
slideElements.push(document.getElementById("slide5"));
var currentSlideIndex = 0;
var numberOfSlides = slideElements.length;
var slideTimeMs = 1000;
// initialize slide elements
for(var i = 0; i < numberOfSlides; i++) {
slideElements[i].style.display = 'none';
}
slideElements[0].style.display = 'block';
// start interval timer
setInterval(function() {
slideElements[currentSlideIndex].style.display = 'none';
currentSlideIndex = (currentSlideIndex + 1) % numberOfSlides;
slideElements[currentSlideIndex].style.display = 'block';
}, slideTimeMs);
I think I understand your question. If you want to rotate through slides and restart when you get to the end here's what I'd do:
Firstly, create a function that we can pass an array of "slides". This function will have local variables that define the index of our current slide, and the index of the last slide (so we know when to restart).
We create a slide function that'll handle getting the elements, hiding/showing the next and previous elements, and incrementing (or resetting) our index.
var rotateSlides = function (slides, delay) {
// Start on the first slide in our list
var currentIndex = 0;
// Our final slide index
var lastIndex = slides.length - 1;
// Our main slide function
var slideFn = function () {
// The next slide, which we will be showing
var next = slides[currentIndex];
// declare previous, will be set later
var previous;
if (currentIndex === 0) {
// Set previous to the last slide in our list if we're current on index 0
previous = slides[lastIndex];
} else {
// Otherwise, set previous to currentIndex - 1
previous = slides[currentIndex - 1];
}
// Hide the previous slide
previous.style.display = "none";
// Show the next slide
next.style.display = "block";
if (currentIndex !== lastIndex) {
// Increment currentIndex if we aren't on our last slide
currentIndex += 1;
} else {
// Reset currentIndex if we ARE on our last slide
currentIndex = 0
}
};
// call our function right away to start it
slideFn();
// set an interval to call our function at the given speed
window.setInterval(slideFn, delay);
}
// Call our rotate function on a list of elemetns and
// pass a duration each slide should be visible for
rotateSlides([
document.getElementById('slide1'),
document.getElementById('slide2'),
document.getElementById('slide3')
], 1000);
<div id="slide1">Slide1</div>
<div id="slide2" style="display: none;">Slide2</div>
<div id="slide3" style="display: none;">Slide3</div>
If you want to slow it down so it takes 6 seconds, change 1000 to 2000 where we call rotateSlides.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Categories