How to move a div from left to right using javascript - javascript

I have div named movingImage that I want to move to the right 50px every time I click a button.
Here's my javascript:
function moving_Image() {
document.getElementById("movingImage").style.right = "50px";
}
And html:
<h1 id="movingImage"> __________ </h1>
<input type="button" value="click me" onclick="moving_Image()">

The element you want to move, needs to have the CSS property position: relative;:
I also changed .style.left to .style.right, you will see why:
var imageOffset = 0
function moving_Image() {
imageOffset += 50
document.getElementById("movingImage").style.left = imageOffset + "px";
}
#movingImage {
position: relative;
}
<h1 id="movingImage">__________</h1>
<input type="button" value="click me" onclick="moving_Image()">
If you don't understand something else, please feel free to ask in the comments.

use this code instead:
<body>
<script>
function movingImage(){
var movingImage = document.getElementById("movingImage").style.left;
movingImage.style.left = movingImage.substring(0,MovingImage.length-1) + 50.toString() + "px";
}
</script>
<h1 id="movingImage" style="position: absolute; left: 0px;">Move Image!</h1>
<input type="button" value="Move, Move Image!" onclick="movingImage()">
</body>

I think CodeiSir has it covered, but I wanted to share a few notes that I made playing around with the code about some general JavaScripty things, as well as a couple of new things I learned today.
1) Separate your JS from your HTML.
This
<input type="button" value="click me" onclick="moving_Image()">
would become
<button>Click me</button>
and
document.querySelector('button').onclick = moving_Image;
2) There's an element called offsetLeft (also offsetRight, obvs) which is a read-only attribute that shows by how much the upper left corner of the current element is offset to the left. So we can, for example, write:
div.style.left = (div.offsetLeft + amount) + 'px';
3) It might be fun to have a range of buttons that move the element different amounts, perhaps by adding data attributes to the buttons:
<button data-amount="50">by 50</button>
We can then process that amount using the dataset attribute in the function.
function movingImage(e) {
var amount = +e.target.dataset.amount;
div.style.left = (div.offsetLeft + amount) + 'px';
}
The code in full. Note I'm also passing in the div element with the click event.
HTML
<div id="movingImage"> __________ </div>
<button data-amount="5">by 5</button>
<button data-amount="20">by 20</button>
<button data-amount="50">by 50</button>
JS
function movingImage(el, e) {
// adding a preceding + coerces the string to an integer
var amount = +e.target.dataset.amount;
el.style.left = (el.offsetLeft + amount) + 'px';
}
var div = document.getElementById("movingImage");
var buttons = document.querySelectorAll('button');
// [].slice.call basically makes the nodelist an array
// so that you can use the native array functions on it.
[].slice.call(buttons).forEach(function (button) {
// here were just binding the div element to the click
// event. We could just have easily written
// button.onclick = movingImage;
// and then referred to div instead of el in the function
button.onclick = movingImage.bind(this, div);
});
DEMO

This is My Version to move a div left to right using javascript:
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
position: absolute;
background-color: coral;
color: white;
}
</style>
</head>
<body>
<p>
Click the "Try it" button to position the DIV element 100 pixels from the right edge:
</p>
<p>
<strong>Note:</strong> If the position property is set to "static", the right property has no effect.
</p>
<button onclick="myFunction()">Try it</button>
<div id="movingImage">
This is My Div!!
</div>
<script>
function myFunction() {
let movingImage = document.getElementById("movingImage");
if (movingImage.style.right = "100px") {
movingImage.style.right = "0px";
} else {
movingImage.style.right = "100px";
}
}
</script>
</body>
</html>
src: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_left
https://www.w3schools.com/jsref/jsref_if.asp

Related

how to create dynamic squares with HTML and CSS

My goal is to create 3 inputs where you can choose the color of the cube, the size and the amount of cubes. The picture down below is my classmates final work but he wouldn't give me the code. We were given a template to start on and this is what I have so far.
<style>
.square {
height: 50px;
width: 50px;
background-color: var(color1);
}
</style>
<script>
function makeSquare(size, color){
var div = document.createElement("div");
div.style.display = "inline-block";
div.style.height = size+"px";
div.style.width = size+"px";
div.style.backgroundColor=color;
div.style.margin="5px";
document.body.appendChild(div);
}
function addSquares(){
if (inputColor == "blue")
var color1 = '#555';
}
</script>
</head>
<body>
<p>Number of squares:<input type="text" id="inputNumber"></p>
<p>Color of squares:<input type="text" id="inputColor"></p>
<p>Size of squares:<input type="text" id="inputSize"></p>
<button onclick=addSquares()>Add squares</button>
<div class="square"></div>
</body>
</html>
as you can maybe guess, this does not work and I have no clue how to do this...
I hope you can help me
For example have a look at jQuery css() method. There you can add or remove css styling from an element. I will not post a solution for you because this is clearly your homework but research around this topic and you can handle this task easily.
I am showing you a way to correct your code,
I can't see where you have called makeSquare().
In addSquares(), did you get value of inputColor?
you need to get value of each input and pass SIZE, COLOR(if its not fetched and set earlier stage) and NUMBER in makeSquare()
Need to loop NUMBER's time to get block in body. inside that create you square block with COLOR and SIZE.

How to set order to arrays when I click next and previous on JavaScript?

I want to create a image viewer where you click next and previous to change the image.
So far the buttons next and previous changes the image. However when I click next then previous, the image doesn't go to the previous image instead it goes to the starting image.
My guess is to create a variable var = newImage and use that variable on function change2() and create a new varirable var= newImage2 and use that on function change().
is that possible?
<!DOCTYPE html>
<html>
<head>
<title>JS ChangeImage</title>
</head>
<body>
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change2()">Previous</button>
<img src="html5.png" style="height: 500px; width: 500px" id="changeimg">
<button onclick="change()">Next</button>
</div>
</body>
<script>
var img=0;
var imgArr = ["html5.png","css3.png","javascript.png"]
function change() {
var image = document.getElementById('changeimg');
console.log("current image =>", imgArr[img])
document.getElementById('changeimg').src =imgArr[img];
if (img== 2) img = 0;
else
img++;
}
function change2() {
var c1=
document.getElementById('changeimg').src =imgArr[img];
console.log("current image =>", imgArr[img])
if (img== 0) img = 2;
else
img--;
}
First, I noticed that you are changing the img variable after assigning the image to the element. I think you should switch the order. The way it is now, when you click Next, the number advances, but the picture is associated with the previous number. If you then click Previous, the number will reduce, but the image will appear to advance.
I've made some other changes for simplicity here:
HTML:
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change(event)" name='1'>Previous</button>
<img src="html5.png" style="width: 500px" id="changeimg">
<button onclick="change(event)" name='2'>Next</button>
</div>
JS:
var currentImg = 0;
const imgArr = ["html5.png","css3.png","javascript.png"]
const change=(event)=>{
if(event.target.name==='1'){
currentImg>0?currentImg--:currentImg=2;
} else if(event.target.name==='2'){
currentImg<imgArr.length-1?currentImg++:currentImg=0;
}
console.log(currentImg);
document.getElementById('changeimg').src = imgArr[currentImg];
}
Please note the use of the 'name' attribute of the for use in the logic of the change function. This allows me to use only one function for both buttons. I hope this helps.

How do I move an HTML div using JavaScript?

I want my div containing text to move 10px to the right everytime upon click.
Here is the HTML:
<div id='color-div' style='clear:both; position:relative; left:0;'> </div>
And the script:
document.getElementById('color-div').style.right='10px';
My event is already defined and everything else is working as it should.
To move the div to the right, you should add to left, not right
You need to add a clickhandler to your div.
You are setting the style to a fixed value, to increasing it.
Add
onclick="moveRight()"
to your div, and change your javascript to this:
var moveRight = function(){
var current_offset = parseInt(document.getElementById('color-div').style.left);
document.getElementById('color-div').style.left = current_offset + 10 + "px";
}
Check it out here: jsFiddle
you might like to use this little javascript
<script language="javascript">
function example_animate(px) {
$('#example').animate({
'marginLeft' : px
});
}
</script>
<input type="button" value="Move Right" onclick="example_animate('+=50px')" />
and instead of moving it on button click, call this function on div click event.
Using jquery you can achieve this with : Example
HTML :
<div class="click-me"></div>
CSS :
.click-me {
display:block;
height:50px;
width:50px;
background:blue;
position:absolute;
}
Javascript :
$(document).ready(function() {
$('.click-me').click(function() {
$this = $(this);
var currentLeft = $this.offset().left;
$this.css("left", currentLeft + 10);
});
});

Change image onclick with div toggle

I have some code I'm working on that toggles a div of information depending on the user clicking an image. What I'm looking for is assistance in getting the image to swap when the user clicks, then to swap back when it's clicked again. The image should be changing to: https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif
I'm a newbie when it comes to coding with JS, so any help provided would be much appreciated!
<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block";
}
else{
e.style.display="none";
}
return true;
}
</script>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para1')" value="Toggle"><br>
<div id="para1" style="display:none">
This is my text for section 1!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para2')" value="Toggle"><br>
<div id="para2" style="display:none">
This is my text for section 2!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para3')" value="Toggle"><br>
<span id="para3" style="display:none">
This is my text for section 3!
</span>
You've got the right idea. What I did for this case was add an id to each image with the name of the div + _img -- grabbed that element the same way, then updated the src:
javascript
function toggleMe(a){
var e=document.getElementById(a);
var i=document.getElementById(a+'_img');
if(!e)return true;
if(e.style.display=="none"){
i.src="https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif"
e.style.display="block"
}
else{
i.src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif"
e.style.display="none"
}
return true;
}
html
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para1')" value="Toggle" id="para1_img"><br>
<div id="para1" style="display:none">
This is my text for section 1!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para2')" value="Toggle" id="para2_img"><br>
<div id="para2" style="display:none">
This is my text for section 2!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para3')" value="Toggle" id="para3_img"><br>
<span id="para3" style="display:none">
This is my text for section 3!
</span>
here's a working example: http://jsfiddle.net/8h4T7/1/
PURE CSS
There's no need to use JS.
Here you go with a simple HTML / CSS solution:
LIVE DEMO
<input id="_1" class="toggler" type="checkbox">
<label for="_1"></label>
<div>This is my text for section 1!</div>
CSS:
.toggler,
.toggler + label + div{
display:none;
}
.toggler + label{
background: url(https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif);
position:relative;
display:inline-block;
width:11px;
height:11px;
}
.toggler:checked + label{
background: url(https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif);
}
.toggler:checked + label + div{
display: block;
}
The good part is that both your images are loaded in the browser so there won't happen an useless image request to the server (creating a time-gap) with no image visible (while it's loading).
As you can see the trick is to hide the checkbox and the div,
than using the :checked state you can do your tricks.
PURE JS
If you really want to play with JS than here's some changes to simplify the HTML markup:
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" value="para1"><br>
<div id="para1" style="display:none">This is my text for section 1!</div>
Note that I've changed the useless value to something useful, and removed the unnecessary ID from your inputs. Also, I've removed the messy HTML inline onclick callers. They're hard to maintain in production.
The input value will now help us to target your ID containers.
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
function toggleFn(){
var tog = this.tog = !this.tog;
var targetEl = document.getElementById(this.value);
targetEl.style.display = tog ? "block" : "none";
this.src = imgSRC + (tog?"collapse":"expand") + ".gif";
}
var $para = document.querySelectorAll("[value^=para]");
for(var i=0; i<$para.length; i++) $para[i].addEventListener('click', toggleFn, false);
LIVE DEMO 1
Another JS version:
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
function toggleFn(){
var el = document.getElementById(this.value);
el.style.display = el.style.display=='none' ? "block" : "none";
this.src = imgSRC +(this.src.match('expand') ? "collapse" : "expand")+ ".gif";
}
var $para = document.querySelectorAll("[value^=para]");
for(var i=0; i<$para.length; i++) $para[i].addEventListener('click', toggleFn, false);
LIVE DEMO 2
jQuery VERSION
Having the exact same as above HTML this is the needed jQuery code:
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
$(':image[value^="para"]').click(function(){
var tog = this.tog = !this.tog;
$('#'+ this.value).fadeToggle(); // or use .slideToggle();
this.src = imgSRC + (tog?"collapse":"expand") + ".gif";
});
LIVE DEMO
The interesting part of the code above is the way we store the current state directly into the this element reference Object:
var tog = thistog = !this.tog;
and using a set negation we create the toggle state.
Instead, if you're familiar with the bitwise XOR operator you can use it (to achieve the same) like:
var tog = this.t ^= 1;
XOR DEMO
Using jQuery
You can also use jQuery. It's a tool designed to help young coders. It allows manipulation of JavaScript through minimal functions.
Adding <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> to the head of your document will allow you to use jQuery. Then you can add some style to your collapsibles like this method based on pennstatephil's code.
function toggleMe(a){
var e=$('#'+a);
var i=$(a+'_img');
if(!e) return false;
if(e.css('display') == "none" ) {
i.attr('src', 'https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif');
e.fadeIn('slow');
}
else {
i.attr('src', 'https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif');
e.fadeOut('fast');
}
return true;
}
And an example can be seen here
jQuery API Documentation can be found here

Copying stored text in a table and then display it back into a textarea

I need your help,
How can I go about copying text (with the line breaks included) from my table and put it back into the textarea “newtext”
My existing coding doesn't seem to be working.
<html>
<head>
<style type="text/css">
.box { width: 400px; height: 50px; }
</style>
<script type="text/javascript">
function ta() {
taValue = document.getElementById("ta").value
taValue = taValue.replace(/\n/g, '<br/>')
document.getElementById("tatext").innerHTML = taValue
}
function text2area() {
document.getElementById("newtext").innerHTML = document.getElementById("tatext").innerHTML
}
</script>
</head>
<textarea class="box" id="ta" onkeyup="ta()"></textarea>
<table id="tatable"><tr><td><div id="tatext"></div></td></tr></table>
<br>
<input type="button" onclick="text2area()" value="move text">
<br><br>
<textarea class="box" id="newtext"></textarea>
</html>
Instead of using the function innerHTML, grab the value of the text area you want to capture, and set the value of the new text area to this. You are already using value for the variable taValue. Also, it's better practice to use addEventListener for your clicks and keyups.
function ta() {
taValue = document.getElementById("ta").value
taValue = taValue.replace(/\n/g, '<br/>')
document.getElementById("tatext").value = taValue;
}
function text2area() {
taValue = document.getElementById("ta").value;
document.getElementById("newtext").value = taValue;
}
document.getElementById("ta").addEventListener ("onkeyup", ta, false);
document.getElementById("move-text").addEventListener ("click", text2area, false);
JSFiddle: http://jsfiddle.net/tMJ84/1/
textarea does not have an innerHTML. Notice how you grabbed the value? Set it the same way! It is like this because it is a form element.
document.getElementById("tatext").value = taValue; //semi-colons are just good practice
and here:
document.getElementById("newtext").value = document.getElementById("tatext").value;

Categories