getElementById in javascript constructor [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a question about the attached code snippet. What do you think about the element selection. I selected the element by id, but twice. I looking for a solution, when I able to initialize my variable to an element object.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function Navigation(){
stepValue = 50;
horizontalPosition = 0;
verticalPosition = 0;
this.step = function(direction){
if(direction=="left"){
horizontalStep(horizontalPosition-=stepValue);
} else if(direction=="right"){
horizontalStep(horizontalPosition+=stepValue);
} else if(direction=="up"){
verticalStep(verticalPosition-=stepValue);
} else if(direction=="down"){
verticalStep(verticalPosition+=stepValue);
}
}
horizontalStep = function(value){
document.getElementById('slider').style.left=horizontalPosition;
}
verticalStep = function(value){
document.getElementById('slider').style.top=verticalPosition;
}
}
Navigation.prototype = {
left: function(){
this.step("left");
},
right: function(){
this.step("right");
},
up: function(){
this.step("up");
},
down: function(){
this.step("down");
}
}
var Nav = new Navigation();
</script>
</head>
<body>
<input type="button" onclick="Nav.left()" id="left" value="Left" />
<input type="button" onclick="Nav.right()" id="right" value="Right" />
<input type="button" onclick="Nav.up()" id="up" value="Up" />
<input type="button" onclick="Nav.down()" id="down" value="Down" />
<div id="slider" style="width: 200px; height: 200px; background: #ccc000; position: relative;">hello</div>
</body>
</html>
Possible to initialize the variable in the constructor, without window onload like this (item variable):
function Navigation(){
stepValue = 50;
horizontalPosition = 0;
verticalPosition = 0;
item = document.getElementById("slider");
....
If it impossible I will combine with jquery. I think it will be a solution.
Thank you answers and opinion!
Tibi

You should do something like this:
function Navigation() {
var item = document.getElementById('slider');
// ...
}
var Nav = null;
$(function () {
Nav = new Navigation();
});
so that the code doesn't run until the DOM is ready and the #slider element exists. Only at that point can you fetch it from the DOM and save it in a variable.

You can place the <script></script> just before the end of body tag in HTML like this : :
<html>
<head>
</head>
</body>
<!-- put all your html here before the script tag -->
<script>
//place your script here
</script>
</body>
<html>
This will ensure that all you DOM is already loaded in the memory before the script got executed.
Hope that helps.

Related

Div Traversing with jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to know that, when I click on next button than id="upper1" become id="upper2" and id="upper2" become id="upper3" and id="upper3" become id="upper1" and so on.
Jquery
$('#next').click(function() {
var $dives = $('div');
var total_div = $sel.length;
for (var i = 1; i <= total_div; i++) {
$dives.eq(i).attr('id', $dives.eq(i + 1).attr('id'));
}
});
CSS
#upper1{
background-color:red;
}
#upper2{
background-color:yellow;
}
#upper3{
background-color:orange;
}
HTML
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
<button id="next">Next</button>
You may do something like this that may work with any number of element with any IDs:
$('#next').click(function() {
let $sel = $('.container > div')
let l = $sel.length;
let last = $sel.eq(l - 1).attr('id');
for (let i = l - 1; i >= 1; i--) {
$sel.eq(i).attr('id', $sel.eq(i - 1).attr('id'));
}
$sel.eq(0).attr('id', last);
})
#upper1 {
background-color: red;
}
#upper2 {
background-color: yellow;
}
#upper3 {
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
</div>
<button id="next">Next</button>
With jQuery, you may use:
$("#next").click(function() {
var i1 = $("#upper1");
var i2 = $("#upper2");
var i3 = $("#upper3");
i1.attr("id", "upper2");
i2.attr("id", "upper3");
i3.attr("id", "upper1");
});
You will need to put the code inside a block that waits for the page to load like:
$(document).ready(function() {
<code here>
});
The use of attr allows to set a new id to each of the former id´s. Check the jsFiddle.
Also, as noted by other people, this would be better done by having fixed id´s and changing classes that defined the attributes to rotate.
Is changing the ids themselves really the goal or rather swapping the elements? (with contents)
$('#next').click(function(){
$("#container").children().last().prependTo("#container");
})
#upper1{
background-color:red;
}
#upper2{
background-color:yellow;
}
#upper3{
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
</div>
<button id="next">Next</button>
Or if the goal is switching the colours and not the elements themselves, it can be done with classes instead of swapping the ids:
$('#next').click(function(){
$("[class^=upper]").each(function(){
this.className = "upper" + (((this.className.substring(5) + 1) % 3)+1);
});
})
.upper1{
background-color:red;
}
.upper2{
background-color:yellow;
}
.upper3{
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper1">9</div>
<div class="upper2">8</div>
<div class="upper3">7</div>
<button id="next">Next</button>
I guess you actually want to shuffle the divs not replace ids.
let divs = $(yourDivSelector);
divs.first().prepend(divs.last());
This code would move the last to the top and thereby move the rest down one step.

Elements within dynamically created of <div> on each button click is not properly overridden

I am trying to create a comment box where on each submit a new is dynamically created. The inner elements of the <div> being 3 buttons Edit, Post, Cancel and a close icon(image). These are also dynamically created. I finally append them all together. The below code would generate something like the below image on two submits. The error I'm facing is that, whatever <div>'s close icon/button is clicked, always the last <div> is being affected. Here I tried to close 'Hi' but 'hello' is being affected.Also there is a duplication of the <div> on even comments.
Kindly help me correct these issues.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<textarea id="ta" rows="30" cols="30" readonly></textarea>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var newDiv="",i=1,ta="";
function add() {
i++;
ta=document.getElementById('ta');
newDiv = document.createElement("div");
newDiv.id = "d"+i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
newP=document.createElement("BUTTON");
newP.id="p"+i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
newImg=document.createElement("IMG");
newImg.id="i"+i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
newBut1=document.createElement("button");
newBut1.id="b"+i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
newButt1=document.createElement("button");
newButt1.id="bt"+i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
}
</script>
</body>
</html>
Try this code. I have changed textarea to div.
Initial i to 0 instead of 1. You can also set it to 1. It won't affect the functionality.
Some variables were global, I have changed them to local variable now like newDiv,newP, newImg etc.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<!--<textarea id="ta" rows="30" cols="30" readonly></textarea>-->
<div id="ta"></div>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var i=0,ta="";
function add() {
(function(){
i++;
var temp_i = i;
ta=document.getElementById('ta');
var newDiv = document.createElement("div");
newDiv.id = "d"+temp_i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+temp_i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
console.log(temp_i);
console.log(i);
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
var newP=document.createElement("BUTTON");
newP.id="p"+temp_i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
var newImg=document.createElement("IMG");
newImg.id="i"+temp_i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
var newBut1=document.createElement("button");
newBut1.id="b"+temp_i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
var newButt1=document.createElement("button");
newButt1.id="bt"+temp_i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+temp_i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
})();
}
</script>
</body>
</html>
Why not you use jquery to minimize your code campaign. Below is the code which will fix your problem.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<br>
<div class="container">
<input type="textbox" id="tb"><br>
<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br />
</div>
<button class="submit">Submit</button><br>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.submit').click(function() {
var element = '<div class="container">'+'<input type="textbox" id="tb"><br>'+
'<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br /></div>';
$('.submit').before(element);
});
$('body').delegate('.cancel', 'click', function() {
$(this).parent().remove();
});
});
</script>
</body>
</html>
Thanks

how we can apply if else condition on css properties using javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to put condition on CSS properties in JavaScript. What is the easiest way to do this?
<html>
<head>
<title>TOOLTIP USING JAVASCRIPT</title>
<style>
span{
cursor: pointer;
}
#demo{
background-color:cadetblue;
color:white;
width:150px;
padding:10px;
font-size:12px;
position:absolute;
top:20px;
left:60px;
display:none;
}
</style>
<link href="font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<br><br><br><br>
<label for='name'>NAME </label>
<span id="s1" style="color:#00b1ff;font-size:15px" class="fa fa-info-circle"> :</span>
<p id="demo">Please Enter Only Characters</p>
<input type="text" name="name" placeholder="Enter The Name ">
<script type="text/javascript">
if(con.style.display="none")
{
code here....
}
</script>
</body>
</html>
use javascript getComputedStyle & getPropertyValue property.
HTML
<div id="conditionals">Change this text here</div>
CSS
#conditionals {
display: none;
}
Javascript
var element = document.getElementById("conditionals");
var compStyle = window.getComputedStyle(element);
var prop = compStyle.getPropertyValue('display');
alert(prop);
Now you will get the prop value to be none and use if/else conditions to show manipulate the css and html
if(prop) {
/**code here **/
}
else {
/** code here **/
}
With jquery:
$(document).ready(function(){
var x= $('.yourSelector').css('display');
if (x == 'none') {
//Your code.....
}
})
$(document).ready(function(){
var x= $('.x').css('display');
if (x == 'none') {
alert('display is None');
}
else {
alert('display is not none')
}
})
.x {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="x"></div>

previous button not working

Hello guys i have creates this code but it's not working in which way i want it to work
i have added some colors here and i want them to come in one by one after i click next button,next button is working propely but when i press previous button it's adding +1 then then go -1 hope you understand what i am trying to ask
thank you
it's only javascript,html and css
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#box{width: 500px; height: 400px; background: #CCC;}
</style>
</head>
<body>
<div id="box"></div>
<input type="button" value="NEXT" onclick="changecolor()">
<input type="button" value="PREVIOUS" onclick="prevcolor()">
<script type="text/javascript">
var boxcolor=["pink","blue","orange","magenta"];
var i=0;
function changecolor(){
var div=document.getElementById('box');
div.style.background=boxcolor[i];
i++;
if(i==boxcolor.length){
i=0;
}
}
function prevcolor(){
var div=document.getElementById('box');
div.style.background=boxcolor[i];
i--;
if(i==boxcolor.length){
i--;
}
}
</script>
</body>
</html>
You first set the color and only then increment/decrement i:
div.style.background=boxcolor[i];
i--;
So when you have this sequence:
i = 0, color=grey (not set yet)
click NEXT
color=pink, i becomes 1
click NEXT
color=blue, i becomes 2
click PREVIOUS
color=orange, i becomes 1
See how i is always set to the next color? So no matter what button you click, the next color is already determined by your previous click.
You can easily catch this type of problem by stepping through your code in a debugger.
Update
Below is a working code snippet that is a bit easier to follow by splitting the increment/decrement from the actual changing of the color.
var boxcolor=["pink","blue","orange","magenta"];
var i=0;
changecolor();
function changecolor(){
var div=document.getElementById('box');
div.style.background=boxcolor[i];
}
function nextcolor() {
i++;
if(i==boxcolor.length){
i=0;
}
changecolor();
}
function prevcolor(){
i--;
if(i==-1){
i = boxcolor.length-1;
}
changecolor();
}
#box{width: 200px; height: 100px; background: #CCC;}
<div id="box"></div>
<input type="button" value="NEXT" onclick="nextcolor()">
<input type="button" value="PREVIOUS" onclick="prevcolor()">
A possible solution could be this one:
Javacsript:
var boxcolor=["pink","blue","orange","magenta"];
var div=document.getElementById('box');
var len = boxcolor.length;
var i=0;
changeColor();
function changeColor(){
div.style.background=boxcolor[i];
}
function nextcolor(){
i = (i+1) % len;
changeColor();
}
function prevcolor(){
i = (len+(i-1)) % len;
changeColor();
}
HTML:
<div id="box"></div>
<input type="button" value="NEXT" onclick="nextcolor()">
<input type="button" value="PREVIOUS" onclick="prevcolor()">
CSS:
#box{
width: 500px; height: 400px;
}
Check this link jsfiddle to see a working example. Hope it's useful!

How to import images/change them on button click? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
in home page there is 3 images and 2 buttons named next and previous. when next button is clicked the 3 images will changed to next 3 images. total images are 100. then next is clicked new 3 images displays. on third click, only the last one image will shows.
on previous button click do reverse. the code is in below , not completed
<html>
<head>
<title>
Check! 1
</title>
<style type="text/css">
#myimage {
position:absolute;
left:800;
top:500;
height: 50px;
width: 50px;
}
#myimage1 {
position:absolute;
left:500;
top:500;
height: 50px;
width: 50px;
}
#imageDiv
{
position:static;
top: 50px;
left: 10px;
}
</style>
<script type="text/javascript">
var count=0;
function image(thisImg) {
var img = document.createElement("IMG");
img.src = "img/"+thisImg;
document.getElementById('imageDiv').appendChild(img);
}
function test()
{
//alert("just checking yaar");
if(count<4)
{
++count;
console.log("count",count);
if(count==1)
{
image('44585_Murree-Best-Hill-Station-wallpapers- pictures_640x320.jpg');
image('91517_background-painting-used-Main-Menu-screen_640x320.jpg');
image('gravityflue04-640x320.jpg');
}
else if(count==2)
{
image('44585_Murree-Best-Hill-Station-wallpapers-pictures_640x320.jpg');
image('91517_background-painting-used-Main-Menu-screen_640x320.jpg');
image('gravityflue04-640x320.jpg');
}
else if(count==3)
{
image('44585_Murree-Best-Hill-Station-wallpapers-pictures_640x320.jpg');
image('91517_background-painting-used-Main-Menu-screen_640x320.jpg');
image('gravityflue04-640x320.jpg');
}
else if(count==4)
{
image('44585_Murree-Best-Hill-Station-wallpapers-pictures_640x320.jpg');
image('91517_background-painting-used-Main-Menu-screen_640x320.jpg');
image('gravityflue04-640x320.jpg');
}
else
{
console.log("Invalid Count");
}
}
}
function test2()
{
if(count>0)
{
--count;
console.log("count",count);
}
else
{
console.log("Invalid Count");
}
}
</script>
</head>
<body>
<input type="image" id="myimage" value="next" name="next" src="next-button.jpg" onclick="test()">
<input type="image" id="myimage1" value="" name="next" src="111645-glowing-green-neon-icon-media-a-media31-back.png" onclick="test2()">
Load the array with the names of the images. The number of empty <img /> tags (in the images <div />) dictate how many images display at once. Change the displayImage to point to the folder that contains the images.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<button onclick="previous();">previous</button>
<div id="images">
<img />
<img />
<img />
</div>
<button onclick="next();">next</button>
<script>
var imageSources = Array(
"orderedList0.png", "orderedList1.png", "orderedList2.png",
"orderedList3.png", "orderedList4.png", "orderedList5.png",
"orderedList6.png", "orderedList7.png", "orderedList8.png",
"orderedList9.png");
var firstImage = 0;
var increment = document.getElementById("images").children.length;
displayImages();
function next() {
if (firstImage + increment < imageSources.length) {
firstImage += increment;
}
displayImages();
}
function previous() {
if (firstImage - increment >= 0) {
firstImage -= increment;
}
displayImages();
}
function displayImages() {
var imageDiv = document.getElementById("images");
for (var imageIndex = 0; imageIndex < imageDiv.children.length ; imageIndex++) {
displayImage(imageDiv.children[imageIndex], imageSources[firstImage + imageIndex])
}
}
function displayImage(image, src) {
if (src) {
image.src = "images/" + src;
image.style.display = "";
} else {
image.style.display = "none";
}
}
</script>
</body>
</html>
That is probably easiest to solve with jQuery.
Here is a solution you can use: http://jqueryfordesigners.com/demo/infinite-carousel-loop.html
And here is the tutorial: http://jqueryfordesigners.com/automatic-infinite-carousel/

Categories