I'm trying a simple thing with each & setTimeout function. I want the letters of a name will appear distinctively & at separate(gradual) time. Suppose, letters of NAZ should appear this way, first N second A last Z. but, here I can see output is AZN then ZNA then NAZ. What I feel, I've a wrong comprehension of how 'each' works actually. but, the output in console is shown exactly as I intended. Have a look at this.
$('div.promise').each(function(index, promise){
setTimeout(function()
{
$('.showPromise').append(promise);
console.log($(promise).text());
$('.promise').css({"display":"block"})},1000*(index+2));
});}
https://jsfiddle.net/sanje/425konu3/17/
How can I show the output as shown in console? & why all the divs appear altogether at certain time? Please help me find out the mistake. Thanks!
The problem is following statement inside your setTimeout:
$('.promise').css({"display":"block"})
It makes all div's with class promise visible together. You should use this instead:
$(promise).css({"display":"block"})
var showAnimation=function(){
$('div.promise').each(function(index, promise){
setTimeout(function(){
// $('.showPromise').append(promise);
console.log($(promise).text());
$(promise).css({"display":"block"})
},1000*(index+2));
});//each()
}//showAnimation()
$('button').on('click', showAnimation);
.promise {
display: none;
padding: 10px;
}
.showPromise {
background-color: red;
margin: 10px;
display: flex;
height: 100px;
width: auto;
}
.as-console-wrapper{display: none !important;}
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<button>call</button>
<div class="showPromise">
<div class="promise">N</div>
<div class="promise">A</div>
<div class="promise">Z</div>
</div>
You are setting display on the whole class each time. You need to only show each instance in the loop. you can simplify and do that using show().
The append() part doesn't really make much sense either so I removed it
var showAnimation = function() {
$('div.promise').each(function(index, promise) {
setTimeout(function() {
$(promise).show();
}, 1000 * (index + 2));
});
}
$('button').on('click', showAnimation);
.promise {
display: none;
padding: 10px;
}
.showPromise {
background-color: red;
margin: 10px;
display: flex;
height: 100px;
width: auto;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<button>call</button>
<div class="showPromise">
<div class="promise">N</div>
<div class="promise">A</div>
<div class="promise">Z</div>
</div>
#charlietfl Perhaps, I could figure out what's happened here. Please have a look at the existing code
$('.showPromise').append(promise);
$('.promise').show();},1000*(index+2));
https://jsfiddle.net/425konu3/20/
output:
AZN (shows then hides)
ZNA (shows then hides)
NAZ (persists)
I asked what’s hack here, why not NAZ NAZ NAZ. It turns out that as append moves the selected element as the last child & all the divs are available to display right at the moment by virtue of $('.promise').show(), they are shown up altogether in a manner that the first div is appended as last while the next adjacent div sits at 0 index & the rest sits next to it.
First time, N appends(last index), A(index 0), Z(index 1), so AZN appears.
Second time, A appends(last index), Z(index 0), N(index 1), so ZNA appears.
Last time, Z appends(last index), N(index 0), A(index 1), so NAZ appears.
Related
I've coded a very simple slide show, that shows a new slide every 5 seconds. The slide show image names are: 1.png, 2.png, 3.png, etc. There is a total of 5 slides. When I refresh my browser, the slide show doesn't work. For the record, I coded this with the help of w3schools.com and other tutorials, and I literaly copied the code from the sites(of course I changed the variables). Even though I did that, it still doesn't work. Pls help.
JS code(in ):
<script type="javascript">
var number=0;
function change_slide() {
number++;
if(number>5) {
number=1;
}
document.getElementById( "slider" ).style.backgroundImage="url(number + '.png')";
setInterval(change_slide, 5000);
}
</script>
in body tag:
<body onload="change_slide()">
slide show div
<div id="slider"></div>
slide show css
#slider {
float:left;
width:505px;
height:330px;
margin-right: 50px;
margin-left: 25px;
margin-top: 25px;
border:2px solid black;
border-radius: 15px;
}
Sorry for no code snippet, but the code of the site is to long.
PS.all slide show images all have dimentions of: 505x330 pixels.
The issue is in this line here:
document.getElementById( "slider" ).style.backgroundImage="url(number + '.png')";
You put the var number inside of double quotes, which treats it as a string and not a variable. Change it to this:
document.getElementById( "slider" ).style.backgroundImage="url(" + number + ".png)";
you could consider changing your function to:
<script>
var number = 0;
function change_slide() {
number = ++number % 5;
document.getElementById("slider").style.backgroundImage = ["url('", number, "'.png')"].join("");
setTimeout(change_slide, 5000);
}
</script>
This culprit line should be as pointed out by #Matt L.
So I don't get why this isn't working. I want to show a Div when another div has a value. I got this code from stackoverflow and it's pretty simple. But it doesn't work for me. No console errors..
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
});
If the html value of .txt is larger then 0 then show btn-01.
But it doesn't. In my web inspector it just says:
<div style="display: block;" class="btn-01"><p>Things</p></div>
If I remove the script it says:
<div class="btn-01"><p>Things</p></div>
So it does do something. I tried changing the show to hide. But no go.
<div style="display: none;" class="btn-01"><p>Things</p></div>
I tried:
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').addClass('showme);
}
});
btn-01 css:
.btn-01 {
background: #f60;
color: #fff;
border-radius: 2px;
padding: 5px;
text-align: center;
margin: 40px auto 0px auto;
width: 90%;
}
But that didn't work either. Does anyone know whats going on here?
Maybe I should work with an else statement? Help would be much appreciated.
JsFiddle
You need to either set the button to display none prior to the window loading or add an "else" statement to hide the element:
.btn-01{
display:none;
}
OR
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
else
{
$('.btn-01').hide();
}
});
See the fiddle: https://jsfiddle.net/r89gg7tp/
IMPORTANT TO CONSIDER
If you have entered a line break between the starting and closing tags of the element, this will add to the length. You need to set the txt div to be in the following format:
<div class='txt'></div>
It may be better to change your function to this:
$(document).ready(function(){
if ($(".txt").html().trim(' ').length > 0) {
$('.btn-01').show();
} else {
$('.btn-01').hide();
}
});
This way you trim the whitespace before checking.
See the second fiddle: https://jsfiddle.net/r89gg7tp/3/
You need to hide the btn-01 with a "display:none" in the stylesheet and then execute your script.
I think you are having a "display:none !important" which is overriding the jquery show() function inline style.
This might help you.
$(document).ready(function(){
if (!$.trim($(".txt").html())){
$('.btn-01').addClass('showme');
}
});
Please let me know if you've any queries.
You can use .contents() with .toggle():
$(document).ready(function() {
$('.btn-01').toggle($(".txt").contents().length > 0);
});
.btn-01{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="txt">
<h3>Things Title</h3>
</div>
<div class="btn-01">
<p>Things</p>
</div>
You guys where all right. I needed to place the code in some Session file (Ajax). Now its working with the original code and even some that you provide.
Thanks!
I have a JavaScript function that displays text based on input in a text field. When a value is entered into the text field, my program will check to see if the value is correct. If it is correct, my program displays, "You are correct!" and if it is incorrect, my program displays, "Try again!"
The text field and button are both centered horizontally on the page, but I cannot figure out how to center the "You are correct!" and "Try again!"
I feel like I have tried everything, but obviously I haven't, considering I can't get it to work.
Here is the code for my JavaScript function:
<center><p>Can you remember how many books I listed at the bottom of the page?</p></center>
<center><input id="numb"></center>
<center><button type="button" onclick="myFunction()">Submit</button></center>
<p id="demo"></p>
<div class="jsFunction">
<script>
function myFunction()
{
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than five or greater than five
if (isNaN(x) || x < 5 || x > 5)
{
text = "Try again!";
}
else
{
text = "You are correct!";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</div>
Here is the CSS code for the function:
.jsFunction
{
margin-left: auto;
margin-right: auto;
}
This specific CSS code is only one of many, many attempts I have made at centering the text in the function.
Here is a link to a picture that will show you the problem I am having:
http://i.stack.imgur.com/Hb01j.png
Please help!
Try setting a class on the p tag that contains text-align: center;
Edit
Nesting your script in a div is meaningless as script tags don't get rendered
You can either target #demo in your css (for the text alignment) or add a class align-center that contains the correct style.
I would recommend the latter as the becomes more reusable, whereas you can't reuse an id on the same page
The fact that you are using JavaScript isn't important to this question. I mention it because of the title "How to Center Text in a JavaScript Function" and your attempt to center the actual script element containing your JavaScript code.
You want to center the contents of an element that happens to be controlled by JavaScript, but the answer is CSS-only.
As Ryuu's answer mentions, text-align: center will do the job for (you guessed it) text and other inline-level content.
You should not use the deprecated center tag.
Your attempt to use margins will center something if you apply it to the correct element and the element has a width. That "something" is the element, however, not the contents of the element.
In other words, margin can be used to align the box, not the stuff within the box.
Example 1: centers the element, but the text is still left-aligned.
Example 2: centers the element and its inline-level contents.
.margin-example1 {
width: 200px;
background-color: #ddd;
/* shorthand for margin: 0 auto 0 auto, which is shorthand for specifying each side individually */
margin: 0 auto;
}
.margin-example2 {
width: 200px;
background-color: #aaccee;
margin: 0 auto;
/* we still need this to get the desired behavior */
text-align: center;
}
<div class="margin-example1">Example 1</div>
<div class="margin-example2">Example 2</div>
So how about a text input? Browsers usually style inputs as display:inline-block. This means we can center something inside them (Examples 1 & 2), but to center them within their container we need to change to display:block (Example 3) or because they are inline-like elements themselves, we can set text-align on the parent container (Example 4), see also.
.example1 {
width: 100%;
text-align: center;
}
.example2 {
width: 200px;
text-align: center;
}
.example3 {
display: block;
width: 200px;
text-align: center;
margin: 0 auto;
}
.example4 {
width: 200px;
text-align: center;
}
.example4-parent {
text-align: center;
}
<div>
<input type="text" value="Example 1" class="example1">
</div>
<div>
<input type="text" value="Example 2" class="example2">
</div>
<div>
<input type="text" value="Example 3" class="example3">
</div>
<div class="example4-parent">
<input type="text" value="Example 4" class="example4">
</div>
Layout in CSS can be complicated, but the basics aren't hard.
Note that I have over-simplified my explanation/definitions a bit (you can read all about the formatting model when you are ready).
I have a simple script that creates and deletes divs when pushing buttons.
$("#add").click(function(){
$(document.body).append('<div class="bloc">'+(++_INDEX)+'</div>');
});
$("#del").click(function(){
$(".bloc:first").remove();
});
My issue is with the "Delete" part, I need all the divs to stay at their current position when deleting anything.
And once I recreate new ones, they should take up the blank space left from previously deleted ones.
Could this be done through HTML/CSS only ? If not, how can I solve this ?
Please see the code example here: https://jsfiddle.net/t6wvLyjb/
It is difficult to do that because once a div has been removed from the dom rest of the elements will rearrange. One way to do is create elements absolutely(which is also difficult) and store their locations. While deleting you will not have a problem but while adding you have to add them to the previously stored locations.
Another option is to change the visibility of blocks instead of removing them. When adding instead of creating new ones first make all the blocks visible first and then create new ones.
You can do something like this
var _INDEX = 0;
$(document).ready(function(){
$("#add").click(function(){
if(!$('.bloc.removed').length){
$(document.body).append('<div class="bloc">'+(++_INDEX)+'</div>');
}else{
$(".bloc.removed").first().removeClass('removed');
}
});
$("#del").click(function(){
$(".bloc:not(.removed)").first().addClass('removed');
});
});
var _INDEX = 0;
$(document).ready(function() {
$("#add").click(function() {
if (!$('.bloc.removed').length) {
$(document.body).append('<div class="bloc">' + (++_INDEX) + '</div>');
} else {
$(".bloc.removed").first().removeClass('removed');
}
});
$("#del").click(function() {
$(".bloc:not(.removed)").first().addClass('removed');
});
});
.bloc {
background-color: red;
margin: 8px;
padding: 6px;
float: left;
width: 200px;
height: 64px;
}
.removed {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Add" id="add" />
<input type="button" value="Del" id="del" />
<br/>
Here is a demo https://jsfiddle.net/dhirajbodicherla/t6wvLyjb/1/
Try using CSS making the position fixed or absolute. This way you will have the position of the element fixed to place.
I don't know if it will work when you delete elements but worth a shot.
Problem and source code
I'm trying to create <div>s within another <div> at the click of a button. When the button is clicked, a new inner <div> is created (within the outer <div>) with a unique id. I have this part working but here's where I'm running into an issue: I want each inner <div> to have a random margin-top.
Javascript
function pressButton() {
number += 1;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("innerDiv" + x);
outer.appendChild(innerDiv);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + ";display:inline-block;width:48px;height:48px;background-color:#000;");
};
CSS:
#outer {
position:absolute;
white-space:nowrap;
height:118px;
overflow:auto;
width:100%;
padding:2px;
}
Result (after button is clicked 4 times)
<div id="outer">
<innerDiv1 style="margin-top:15;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv1>
<innerDiv2 style="margin-top:23;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv2>
<innerDiv3 style="margin-top:37;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv3>
<innerDiv4 style="margin-top:0;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv4>
</div>
The result (which I got from inspecting the inner elements in my browser) looks like everything worked - all the margin-tops are random like I wanted. However, the visual result is this:
As you can see, the black inner <div>s all have the same margin-top. What am I doing wrong? How can I make the created <div>s all have random margin-tops?
The CSS spec requires that a length (other than zero) that is missing a unit be treated as an error (and thus ignored). Therefore, add px to the end of your generated margin number, and all should be well.
Live Demo
Description
This happens, because you set the display:inline-block; property. This makes them all to be in one line, so they will allign to the innerDivx that has the highest margin-top.
Delete the display:inline-block; property and give them float:left;. If you want to keep the gap between them, also add margin-left:5px;. And don't forget that margin-top's value needs a unit. I think you wanted to use px.
Also <innerDivx> is not a valid HTML tag. You should change them to a <div> and use innerDivx as an id attribute. Also your tags use almost the same CSS styles so you should put the same ones to a class and add the class instead.
Full solution code
HTML
<button id="button1">Add box</button>
<div id="outer"></div>
JavaScript
var number = 0;
document.getElementById("button1").addEventListener("click", pressButton, false);
function pressButton() {
++number;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(innerDiv);
innerDiv.className += " box";
innerDiv.setAttribute("id", "innerDiv" + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
CSS
#outer {
position: absolute;
white-space: nowrap;
height: 118px;
overflow: auto;
width: 100%;
padding: 2px;
}
.box {
float: left;
width: 48px;
height: 48px;
background-color: #000;
margin-left: 5px;
}
This is likely caused by the position model used for inline-block elements - they're all being vertically-aligned at their bottom line in a row.
I suggest that you simplify this and use position: block with float: left
http://jsfiddle.net/2y5bJ/4/
I also suggest that you stick to standard elements to ensure cross-browser compatibility - don't create your own elements called innerDiv1 etc, but use div elements with unique IDs.
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(div);
innerDiv.setAttribute('id', 'innerDiv' + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
I think there is no tag available with name
<innerDiv1>
This may be the cause.