Make appear text in Javascript - javascript

I'm trying to make appear text in Javascript.
That's my code :
HTML :
<div id="t1">Ecologie</div>
<div id="t2">Planète</div>
<div id="t3">BIO</div>
<div id="t4">Responsable</div>
<div id="t5">Changement</div>
<div id="t6">Durable</div>
<script type="text/javascript">var mytimeout = setTimeout(DisplayElem(), 2000)
</script>
CSS :
#t1
{
position: absolute;
color: green;
font-size: 50px;
top: 50%;
left: 13%;
display: none;
}
#t2
{
position: absolute;
color: green;
font-size: 60px;
top: 40%;
left: 70%;
display: none;
}
and Javascript :
function Display (elem) {
elem.style.display = block;
}
var compteur = 0;
function DisplayElem()
{
compteur += 1;
var id = 't' + compteur;
elem = document.getElementById(id);
Display(elem);
mytimeout = setTimeout(DisplayElem(), 2000)
if(compteur == 6)
{
window.clearTimeout(mytimeout);
}
}
I got this error : Uncaught ReferenceError: block is not defined
on my line :elem.style.display = block;
When i open my page i want all of my div invisible. But after a few second i would like to have on who appear, and the next one, and the next one...
Thank you

Here is your complete working code:
var compteur = 1;
function Display (elem) {
elem.style.display = 'block';
}
function DisplayElem()
{
var id = 't' + compteur;
elem = document.getElementById(id);
Display(elem);
compteur += 1;
if (compteur <= 6)
setTimeout(DisplayElem, 2000);
}
DisplayElem();
See the DEMO here

You have forgotten the delimiters around the string block:
function Display (elem) {
elem.style.display = 'block';
}
Side note: Instead of setting the timeout the last time and then removing it, just skip setting it:
if (compteur < 6) {
mytimeout = setTimeout(DisplayElem(), 2000)
}

Related

how to remove the quotes or get element from this (javascript)

As topic, how can I remove the quote in the picuture below or get the img element from this?
(https://i.stack.imgur.com/kdPAP.png)
I m new to javascript and start making an image slider that can pop up a window while clicked to the image.
I cloned the li object which is clicked, and try to open it in the new window, it do work but how can I get the img only without the li?
Right now i m trying to call the cloned this object with innerHTML, but it shows the img element with quote, is there any way to remove the quote?
the quote that i want to remove
first time ask a question in here, if i violate any rules in the post, i delete the post, sorry for causing any inconvenience.
Here is the code
<!DOCTYPE html>
<html>
<head>
<style>
.risuto1 {
max-width: 480px;
max-height: 270px;
margin: auto;
position: relative;
}
ul {
list-style-type: none;
margin: auto;
padding: 0;
}
.aitemu>img {
max-width: 100%;
}
.aitemu {
display: none;
position: relative;
}
.aitemu.akutibu {
display: block;
}
.risuto1>.mae,
.tsugi {
width: auto;
height: auto;
padding: 20px;
top: 102.6px;
position: absolute;
cursor: pointer;
background-color: red;
}
.risuto1>.tsugi {
left: 431.8px;
}
</style>
</head>
<body>
<script>
var risuto1 = document.createElement("div");
risuto1.classList.add("risuto1");
document.body.appendChild(risuto1);
var suraidaaitemu = document.createElement("ul");
suraidaaitemu.classList.add("suraidaaitemu");
risuto1.appendChild(suraidaaitemu);
var imejisosurisuto = ["https://pbs.twimg.com/media/CGGc3wKVEAAjmWj?format=jpg&name=medium", "https://pbs.twimg.com/media/EYCXvuzU8AEepqD?format=jpg&name=large", "https://s3-ap-northeast-1.amazonaws.com/cdn.bibi-star.jp/production/imgs/images/000/668/074/original.jpg?1626914998", "https://livedoor.blogimg.jp/rin20064/imgs/7/3/73251146.jpg", "https://www.tbs.co.jp/anime/oregairu/character/img/chara_img_02.jpg"]
//var imejirisuto=[]
for (var n = 0; n < imejisosurisuto.length; n++) {
var imeji = document.createElement("img");
imeji.src = imejisosurisuto[n];
var aitemu = document.createElement("li");
aitemu.classList.add("aitemu");
suraidaaitemu.appendChild(aitemu);
aitemu.appendChild(imeji);
aitemu.onclick=atarashivindou;
}
var akutibunasaishonoko = document.querySelector(".suraidaaitemu").firstChild;
akutibunasaishonoko.classList.add("akutibu");
var mae = document.createElement("div");
mae.classList.add("mae");
mae.innerHTML = "&#10094";
risuto1.appendChild(mae);
var tsugi = document.createElement("div");
tsugi.classList.add("tsugi");
tsugi.innerHTML = "&#10095";
risuto1.appendChild(tsugi);
var tensuu = 0;
var suraido = document.querySelector(".suraidaaitemu").children;
var gokeisuraido = suraido.length;
tsugi.onclick = function () {
Tsugi("Tsugi");
}
mae.onclick = function () {
Tsugi("Mae");
}
function Tsugi(houkou) {
if (houkou == "Tsugi") {
tensuu++;
if (tensuu == gokeisuraido) {
tensuu = 0;
}
}
else {
if (tensuu == 0) {
tensuu = gokeisuraido - 1;
}
else {
tensuu--;
}
}
for (var i = 0; i < suraido.length; i++) {
suraido[i].classList.remove("akutibu");
}
suraido[tensuu].classList.add("akutibu");
}
function atarashivindou(){
var Atarashivindou = window.open("", "_blank", "width: 1000px, max-height: 562.5px");
var kakudaigazou=document.createElement("div");
kakudaigazou.classList.add("kakudaigazou");
Atarashivindou.document.body.appendChild(kakudaigazou);
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
}
</script>
</body>
.innerHTML is a string. You don't want to append a string, but the element. So change this:
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
...to this:
var koronimeji=this.querySelector("img").cloneNode();
kakudaigazou.append(koronimeji);

Can't make a simple If Else statement work

Hello I'm making a simple counter that is counting to 3 every time i click the button. The counter works just fine, because I can see how he changes in the console. The problem is, my JS isn't affecting the CSS. When I delete the else statements and leave only one, this is the one that is working.
CSS. note: The strongAttackBtn and strongAttackBtnLoading are in the same div.
.strongAttackBtn {
height: 50px;
width: 150px;
color: black;
font-weight: 800;
}
.strongAttackBtnLoading {
position: absolute;
height: 50px;
width: 150px;
background-color: rgba(0,0,0,0.5);
}
JS
const strongAttackBtnLoading = document.querySelector('.strongAttackBtnLoading');
const strongAttackBtn = document.querySelector('.strongAttackBtn');
let strongAttackCounter = 0;
if (strongAttackCounter === 3) {
strongAttackBtnLoading.style.width = '150px';
} else if (strongAttackCounter === 2) {
strongAttackBtnLoading.style.width = '100px';
} else if (strongAttackCounter === 1) {
strongAttackBtnLoading.style.width = '50px';
} else if (strongAttackCounter === 0) {
strongAttackBtnLoading.style.width = '0px';
}
strongAttackBtn.addEventListener('click', function(){
strongAttackCounter++;
})
Try this code.
You have to assign CSS to both DIVs and put your if statement code in the addEventListener click function.
const strongAttackBtn = document.querySelector('.strongAttackBtn');
const strongAttackBtnLoading =document.querySelector('.strongAttackBtnLoading');
var strongAttackCounter = 0;
strongAttackBtn.addEventListener('click', function(){
strongAttackCounter++;
if (strongAttackCounter === 3) {
strongAttackCounter=0; // set it to zero again;
strongAttackBtnLoading.style.width = '150px';
strongAttackBtn.style.width = '150px';
} else if (strongAttackCounter === 2) {
strongAttackBtnLoading.style.width = '100px';
strongAttackBtn.style.width = '100px';
} else if (strongAttackCounter === 1) {
strongAttackBtnLoading.style.width = '50px';
strongAttackBtn.style.width = '50px';
} else if (strongAttackCounter === 0) {
strongAttackBtnLoading.style.width = '0px';
strongAttackBtn.style.width = '0px';
}
})
.strongAttackBtn {
height: 50px;
width: 150px;
color: black;
font-weight: 800;
}
.strongAttackBtnLoading {
position: absolute;
height: 50px;
width: 150px;
background-color: rgba(0,0,0,0.5);
}
<div class="strongAttackBtnLoading"><input class="strongAttackBtn" type="button" value="strongAttackBtn"></div>

How do I programatically change a picture inside a div?

Here there is full code as you guys can see.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Collage</title>
</head>
<style>
div
{
background: url("Image/191203174105-edward-whitaker-1-large-169.jpg")
;
height: 300px;
width: 300px;
}
</style>
<body>
<div id="div"></div>
<button id="button">Next</button>
<script>
As here I took variable im where I feed 3 images.
var im=[
{'img':'Image/191203174105-edward-whitaker-1-large-169.jpg',}
,{'img':'Image/5718897981_10faa45ac3_b-640x624.jpg',},
{'img':'Image/gettyimages-836272842-612x612.jpg',},
];
var a=document.getElementById('button');
var b=document.getElementById('div')
a.addEventListener('click',next);
so here according to my knowledge it should provide the link of the each pic as loop starts but in program. I dont get the desired result. Can you please help me understand why this is happening?
function next()
{
for(var i=1;i<im.length;i++)
{
b.style.background=`url(${im[i].img})`;
}
}
</script>
</body>
</html>
var i = 0;
var im = [{
'img': 'https://picsum.photos/536/354'
},
{
'img': 'https://picsum.photos/id/237/536/354'
},
{
'img': 'https://picsum.photos/seed/picsum/536/354'
}
];
var a = document.getElementById('button');
var b = document.getElementById('div')
a.addEventListener('click', next);
function next() {
console.log(i);
b.style.background = `url(${im[i].img})`;
i++;
if (i == im.length) {
i = 0;
}
}
div {
background: url("https://picsum.photos/id/1084/536/354?grayscale");
height: 300px;
width: 300px;
}
<div id="div"></div>
<button id="button">Next</button>
If you're looking to cycle through pictures on a button click, then you can't really use a loop. In the code that you posted, on the click of the button, it rapidly looped through all of the pictures. You need to create a counter, and increment it on each button click.
The snippet below I've added in a previous button as well and you can cycle through the pictures both forward and backward.
const im = {
'img1': 'https://placehold.it/300x150/ff0000/ffffff?text=image_1',
'img2': 'https://placehold.it/300x150/00ff00/ffffff?text=image_2',
'img3': 'https://placehold.it/300x150/0000ff/ffffff?text=image_3',
};
const imgDiv = document.getElementById('imgDiv')
const btnNext = document.getElementById('btnNext');
const btnPrev = document.getElementById('btnPrev');
const totImages = Object.keys(im).length;
let imgNumber = 1;
btnNext.addEventListener('click', next);
btnPrev.addEventListener('click', prev);
function next() {
imgNumber++
let img = imgNumber <= totImages ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber === totImages) btnNext.disabled = true;
if (imgNumber > 1) btnPrev.disabled = false;
}
function prev() {
imgNumber--
let img = imgNumber >= 0 ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber < totImages) btnNext.disabled = false;
if (imgNumber === 1) btnPrev.disabled = true;
}
#imgDiv {
background: url("https://placehold.it/300x150/ff0000/ffffff?text=image_1");
height: 150px;
width: 300px;
}
#btnDiv {
width: 300px;
height: auto;
position: relative;
}
#btnPrev {
position: absolute;
left: 0;
top: 0;
}
#btnNext {
position: absolute;
right: 0;
top: 0;
}
<div id="imgDiv"></div>
<div id='btnDiv'>
<button id="btnPrev" disabled>&loarr; Prev</button>
<button id="btnNext">Next &roarr;</button>
</div>

How to prevent centered text in input button be moved when dynamically changed

I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button.
Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text.
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
var dot = '.';
if(dots < 3) {
$('#payDots').val('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').val('processing');
dots = 0;
}
}
<input id="payDots" type="button" value="Pay" class="button">
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
https://jsfiddle.net/v8g4rfsw/1/ (button should be pressed)
The easiest as this is a value and extra elements can't be inserted, would be to just use leading spaces to make the text appear as it's always centered.
This uses the plugin I wrote for your previous question
$.fn.dots = function(time, dots) {
return this.each(function(i,el) {
clearInterval( $(el).data('dots') );
if ( time !== 0 ) {
var d = 0;
$(el).data('dots', setInterval(function() {
$(el).val(function(_,v) {
if (d < dots) {
d++;
return ' ' + v + '.';
} else {
d = 0;
return v.substring(dots, v.length - dots)
}
})
}, time));
}
});
}
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).val('Proccessing').prop('disabled',true).dots(600, 3);
});
});
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="payDots" type="button" value="Pay" class="button">
You can find updated code below
Click Here
HTML Code
<button id="payDots">
<span>Pay</span>
</button>
JS Code
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
$('button').css('padding-left','100px','important');
var dot = '.';
if(dots < 3) {
$('#payDots').text('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').text('processing');
dots = 0;
}
}
CSS Code
button{
text-align: left;
width: 300px;
font-size: 20px;
position:relative;
padding-left:130px;
}

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

Categories