Swap innerHTML for specific time - javascript

I was trying to change the innerHTML of a div and retrieving it again after a certain amount of time.
For that I have implemented sleep(miliseconds) function and used jQuery built-in function as below snippet. The strange thing is that, the code works well in Chrome's debugging mode.
Edited:
I edited the snippet just to show using setTimeout()
is not satisfactory in my special case.
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>");
sleep(time);
$(".classname").html(temp);
}
function foo() {
swap(2000);
$(".tab1").slideToggle("slow");
$(".tab2").slideToggle("slow");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab1">
<div class="classname">
<p>Orginal Content in tab1</p>
</div>
</div>
<div class="tab2" style="display:none;">
<div>
<p>Orginal Content in tab2</p>
</div>
</div>
<button type="button" onclick="foo()">Enter</button>

JavaScript is single-threaded, so your sleep method freezes up the UI and prevents it from refreshing. You should be using setTimeout for this purpose instead.
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>")
setTimeout(function(){
$(".classname").html(temp)
}, time)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classname">
<p>Orginal Content</p>
</div>
<button type="button" onclick="swap(2000)">Enter</button>

Your code just locks up the browser and prevents rendering. You should be using a timeout. This code will make sure that multiple clicks do not mess up the default text.
function swap(selector, time) {
var elem = document.querySelector(selector);
if (!elem.dataset.orgText) elem.dataset.orgText = elem.innerHTML;
if (elem.dataset.timer) window.clearTimeout(elem.dataset.timer);
elem.innerHTML = "<p>Swap Content</p>";
elem.dataset.timer = window.setTimeout( function () {
elem.innerHTML = elem.dataset.orgText;
// delete elem.dataset.orgText;
// delete elem.dataset.timer;
}, time);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classname">
<p>Orginal Content</p>
</div>
<button type="button" onclick="swap('.classname', 2000)">Enter</button>
written for jQuery
function swap(selector, time) {
var elem = $(selector);
if (!elem.data('orgText')) elem.data('orgText', elem.html());
if (elem.data('timer')) window.clearTimeout(elem.data('timer'));
elem.html("<p>Swap Content</p>");
elem.data('timer', window.setTimeout( function () {
elem.html(elem.data('orgText'));
// elem.removeData('orgText');
// elem.removeData('timer');
}, time));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classname">
<p>Orginal Content</p>
</div>
<button type="button" onclick="swap('.classname', 2000)">Enter</button>

You can easily do it with two JQuery Lines:
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>");
setTimeout(function () {
$(".classname").html(temp);
}, time)
}
Please check the Snippet for demo
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>");
setTimeout(function () {
$(".classname").html(temp);
}, time)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab1">
<div class="classname">
<p>Orginal Content in tab1</p>
</div>
</div>
<div class="tab2" style="display:none;">
<div>
<p>Orginal Content in tab2</p>
</div>
</div>
<button type="button" onclick="swap(2000)">Enter</button>

can you try this instead?
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>")
setTimeout(function(){
$(".classname").html(temp);
}, time);
}

function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>")
setTimeout(function(){
$(".classname").html(temp)
}, time)
}
This is the best option!

Related

How can i make function play to run no stop over the divs and how to make function play stop playing after button stop is clicked?

1- I have tried to make the (.up) class (red) keep looping over and over again over the divs after the Play button is clicked but with no success.
2- And I have to somehow stop the (.up) class to be applied from the first function after the button Stop being clicked and be removed all (. up)classes remaining if any.
Any help? I prefer JavaScript or JQuery.
PS: Ignore my cheeky code on the JS for the button (Stop) to try to perform some kind of result.
Thanks
let sequencing = [["01-01", "02-01", "03-01"],["01-02", "02-02", "03-02"],["01-03", "02-03", "03-03"],["01-04", "02-04", "03-04"]];
$("#play").on("click",function(){
play();
});
function play(){
sequencing.forEach((arr, i) => {
setTimeout(() => {
$('.up').removeClass('up');
arr.forEach(id => $('#' + id).addClass('up'));
}, i * 1000);
});
}
$("#stop").on("click", function() {
sequencing.forEach((arr, i) => { setTimeout( () => {
$(".shadowPlay").addClass("shadowPlay").stop();
setInterval(function () {
arr.forEach(id => $("#" + id).removeClass("shadowPlay"));
}, i * 1);
});
}, 1);
});
.up {
background-color: #C00;
color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="play">Play</button>
</div>
<div>
<button id="stop">stop</button>
</div>
<div>
<div id="01-01">01-01</div>
<div id="02-01">02-01</div>
<div id="03-01">03-01</div>
<div id="01-02">01-02</div>
<div id="02-02">02-02</div>
<div id="03-02">03-02</div>
<div id="01-03">01-03</div>
<div id="02-03">02-03</div>
<div id="03-03">03-03</div>
<div id="01-04">01-04</div>
<div id="02-04">02-04</div>
<div id="03-04">03-04</div>
</div>
Consider the following.
$(function() {
$("#play").on("click", function() {
play();
});
function play() {
$(".items").data("interval", setInterval(function() {
var index = 0;
if ($(".up").length > 0) {
index = $(".up:last").index() + 1;
}
$(".up").removeClass("up");
$(".items > div")
.eq(index)
.add($(".items > div").eq(index + 1))
.add($(".items > div").eq(index + 2))
.addClass("up");
}, 1000));
}
$("#stop").on("click", function() {
clearInterval($(".items").data("interval"));
});
});
.up {
background-color: #C00;
color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="play">Play</button>
</div>
<div>
<button id="stop">stop</button>
</div>
<div class="items">
<div id="01-01">01-01</div>
<div id="02-01">02-01</div>
<div id="03-01">03-01</div>
<div id="01-02">01-02</div>
<div id="02-02">02-02</div>
<div id="03-02">03-02</div>
<div id="01-03">01-03</div>
<div id="02-03">02-03</div>
<div id="03-03">03-03</div>
<div id="01-04">01-04</div>
<div id="02-04">02-04</div>
<div id="03-04">03-04</div>
</div>
Instead of a sequence array, you can also simply select each group. Using this as your reference allows the Stop and Start to continue cycling from whatever group was last highlighted.

Displaying an image after clicking 100 times on a button

I'm new here and I still have some difficulties in coding.
I'm trying to create an html page for some friends and I managed to create a click counter, an image which appear and disapear after some time etc
However the only thing that I can't manage to do is how I can make an image appear after clicking on the button for 100 or 1000 times. I can make the image appear after clicking on the button one time, but I don't know how to make it appear only after some clicking.
If someone can help me I'll be very glad!
$button = document.querySelector('button')
$span = document.querySelector('span')
function increment() {
$span.innerHTML++;
}
$button.addEventListener('click', increment);
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
showImage();
setInterval(hideImage, 8000);
}, 5000);
});
function hideImage() {
document.getElementById("imgHideShow").style.display = "none";
}
function showImage() {
document.getElementById("imgHideShow").style.display = "block";
}
<img class="prayme" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Tram_icon_black_and_transparent_background.svg/1024px-Tram_icon_black_and_transparent_background.svg.png">
<p>You prayed <span id='count'>0</span> times</p>
<div id="image">
<img src="https://pbs.twimg.com/profile_images/998926585691451392/WlkEVV7x_400x400.jpg">
</div>
<div class="text-center">
<button><img class="imgbutton" src="https://www.nicepng.com/png/detail/980-9803933_emoji-emoji-pray-thankyou-thanks-praying-hands-emoji.png">
Afficher l'image
</button>
</div>
<div>
<img src="https://i.stack.imgur.com/1dpmw.gif" class="browse-tip" id="imgHideShow">
</div>
You just need to add an if statement, checking if the innerHTML is more or equal to 100, and then call showImage().
I removed code that wasn't relevant.
I added declarations to the variables by adding let in front the name.
I removed the button, and put an event listener directly on the image instead.
I think the rest of the code is self-explanatory.
let spanElement = document.querySelector('span');
let imgButton = document.getElementById('imgbutton');
function increment() {
spanElement.innerHTML++;
if (spanElement.innerHTML >= 5) {
showImage();
}
}
imgButton.addEventListener('click', increment);
document.addEventListener("DOMContentLoaded", function() {
setInterval(hideImage, 8000);
});
function hideImage() {
document.getElementById("imgHideShow").style.display = "none";
}
function showImage() {
document.getElementById("imgHideShow").style.display = "block";
}
img {
height: 3rem;
}
#imgHideShow.hidden {
display: none;
}
<img class="prayme" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Tram_icon_black_and_transparent_background.svg/1024px-Tram_icon_black_and_transparent_background.svg.png">
<p>You prayed <span id='count'>0</span> times</p>
<div class="text-center">
<img id="imgbutton" src="https://www.nicepng.com/png/detail/980-9803933_emoji-emoji-pray-thankyou-thanks-praying-hands-emoji.png">
Afficher l'image
</div>
<div>
<img src="https://i.stack.imgur.com/1dpmw.gif" class="hidden browse-tip" id="imgHideShow">
</div>
To make the code even more readable, I would also add the following it it like this:
Add a constant for how many times the user need to click.
Declare variables for all the elements that are affected.
Use a class (.hidden) to hide the image, and add/remove that class, instead of adding a style. You should only add a style if you can't toggle classes.
const TARGET_TO_SHOW_IMAGE = 5;
let spanElement = document.querySelector('span');
let imgButton = document.getElementById('imgbutton');
let imgHideShow = document.getElementById("imgHideShow");
let numberOfTimesClicked = 0;
function increment() {
numberOfTimesClicked++;
if (numberOfTimesClicked >= TARGET_TO_SHOW_IMAGE) {
showImage();
numberOfTimesClicked = 0; // resets
}
spanElement.innerHTML = numberOfTimesClicked;
}
imgButton.addEventListener('click', increment);
document.addEventListener("DOMContentLoaded", function() {
setInterval(hideImage, 8000);
});
function hideImage() {
imgHideShow.classList.add('hidden');
}
function showImage() {
imgHideShow.classList.remove('hidden');
}
img {
height: 3rem;
}
#imgHideShow.hidden {
display: none;
}
<img class="prayme" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Tram_icon_black_and_transparent_background.svg/1024px-Tram_icon_black_and_transparent_background.svg.png">
<p>You prayed <span id='count'>0</span> times</p>
<div class="text-center">
<img id="imgbutton" src="https://www.nicepng.com/png/detail/980-9803933_emoji-emoji-pray-thankyou-thanks-praying-hands-emoji.png">
Afficher l'image
</div>
<div>
<img src="https://i.stack.imgur.com/1dpmw.gif" class="hidden browse-tip" id="imgHideShow">
</div>

Image is loading as null

I am new to javascript but I am trying to have the default image set with the onload() and I don't think that it is reaching the image that I set up in the array and I cannot figure out why.
I am going to have it rotate images after I click on the button but I can't even get the default image to add.
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=1;
function loadPage()
{
document.getElementById("pictures").src = images[0].src;
}
function nextImage(pictures)
{
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[1].src;
console.log(num++); // I have this just to make sure that it is catching something
}
<div id="maincontent">
<div id="pictures">
<img src="img/mountain.jpg">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
You just need to have your id="pictures" on the image tag, not the div.
Like this:
<img id="pictures" src="img/mountain.jpg">
Also leave off the .src in loadPage() and nextImage()
document.getElementById("pictures").src = images[1];
Here images is an javascript array. So you cannot use .src as it is not an HTML img element
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=1;
//This function will run on body onload
function loadPage()
{
document.getElementById("pictures").src = images[0];
}
//This function will run on button click
function nextImage()
{
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[1];
console.log(num++); // I have this just to make sure that it is catching something
}
<body onload="loadPage()">
<div id="maincontent">
<img id="pictures" src="img/mountain.jpg">
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>
I have updated your code please check.
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=0;
loadPage();
function loadPage()
{
console.log(num);
document.getElementById("picture").src = images[num];
num++;
}
function nextImage(pictures)
{
if(typeof images[num] === 'undefined') {
// does not exist
num = 0;
}
console.log(num);
document.getElementById("picture").src = images[num];
num++;
}
<div id="maincontent">
<div id="pictures">
<img src="img/mountain.jpg" id="picture">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
Try this one:
<script>
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=0;
function loadPage()
{
document.getElementById("pictures").src = images[0].src;
}
function nextImage(pictures)
{
if(num<images.length-1) {
num = num+1;
} else {
num = 0;
}
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[num];
console.log(num); // I have this just to make sure that it is catching something
}
</script>
<div onload="loadPage()">
<div id="imageholder">
<img id="pictures" src="img/mountain.jpg">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>

Button onclick doesn't change style.display of div

I have two divs, called loginpending and loggedin, which I am trying to configure so that once a button (button) is clicked, the divs will "flicker" between one being on and one being off.
For example, in this current state (with loginpending's display as block and loggedin's display as none), once the button is clicked, loginpending's display will become none and loggedin's display will become block through the function loginUpdate, which is then called through launch depending on what the state of each div is.
However, it doesn't work - the state of the buttons don't change at all once the button is clicked.
Help!
HTML code:
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button" onclick="launch()">Hello!</button>
Javascript code (with Jquery):
var logincheck = 0;
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
function launch() {
"use strict";
var loginpending = document.getElementById("loginpending").style.display;
var loggedin = document.getElementById("loggedin").style.display;
window.alert(loginpending);
window.alert(loggedin);
if (loginpending === "none") {
logincheck = 0;
loginUpdate();
} else if (loggedin === "none") {
logincheck = 1;
loginUpdate();
} else {
logincheck = 0;
$("#loggedin").toggle();
}
}
Right now your button is submitting the from which refreshes the page reloadsin its original state.
You need to set the type of button to type="button"
<button id="button" type="button" onclick="launch()">Hello!</button>
$(document).ready(function() {
$('button').on('click', function(){
$('div').toggleClass('hidden');
})
});
.hidden {
display: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="loginpending" class="">
Signup/Login here!
</div>
<div id="loggedin" class="hidden">
Hello!
</div>
<button id="button" onclick="">Hello!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="sample.js"></script>
</body>
</html>
Code with jQuery
I tried to use your original code as much as I could.
var logincheck = 0;
$("#button").click(function() {
launch();
});
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
function launch() {
"use strict";
var loginpending = $("#loginpending").is(":hidden");
var loggedin = $("#loggedin").is(":hidden");
if(loginpending)
logincheck = 0;
else if (loggedin)
logincheck = 1
else
logincheck = 0;
loginUpdate();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button" type="button">Hello!</button>
Gotta try this
$(function() {
var logincheck = 0;
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
$('#button').on('click', function(){
"use strict";
if(logincheck == 0) {
logincheck = 1;
}else{
logincheck = 0;
}
loginUpdate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button">Hello!</button>

Activates javascript after 'x' seconds

Is it possible that the javascript automatically activates after 8 seconds when a user is not using the link, so that it continues every 8 seconds, from Q1 to Q2, Q3 etc
JAVASCRIPT:
function laatZien(divID) {
var tabs = ["Q1", "Q2", "Q3"];
for(var i in tabs)
{ if (tabs[i] != divID)
{
document.getElementById(tabs[i]).className = "verstopt"; b
} }
var item = document.getElementById(divID);
if(item.className=="verstopt") {
item.className = "zichtbaar"
} else {
item.className = "zichtbaar"
}
}
HTML:
<div id="Q1" class="zichtbaar">
Next (Q2)
</div>
<div id="Q2" class="verstopt">
Next (Q3)
</div>
<div id="Q3" class="verstopt">
Back
</div>
CSS:
#Q1.verstopt, #Q2.verstopt, #Q3.verstopt{
display: none;
}
#Q1.zichtbaar, #Q2.zichtbaar, #Q3.zichtbaar{
display: block;
}
simply use the setInterval function provided by javascript and call your method every 8000ms.
setInterval(function(){ laatZien(element) }, 8000);
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
here is a little fiddle for you:
var i = 2;
setInterval(function(){
$('div').removeClass('is_active');
$('.q'+i).addClass('is_active');
if(i == 3) {i = 0;}
i++;
},8000);
.is_active {
display: block;
}
div {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="q1 is_active">Test 1</div>
<div class="q2">Test 2</div>
<div class="q3">Test 3</div>
You can use this function:
var timerId = setInterval(function() {
alert("tick");
}, 2000);
setTimeout(function() {
clearInterval(timerId);
alert('tick');
}, 5000);

Categories