How can I make something move in javascript? - javascript

I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>

Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.

I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!

Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}

Related

Javascript - 2nd button click clears my div

im fairly new to JS and ive created a formula to do some calculations and put them into a div when its done. My problem is on the first button press it works like a charm. When i press the button a second time it deletes the text in my div and doesnt redo the calculation.
Its probably some silly mistake i cant find but id appreciate any help. The Code looks like this:
function formChanged() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
}
document.getElementById('button').click = function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML = "post-text";
}
<form>
<input value="20" id="x" type="text" onkeyup="formChanged()" onchange="formChanged()">
<input value="1" id="y" type="text" onkeyup="formChanged()" onchange="formChanged()">
<button type="button" id="button">Calc</button>
</form>
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
I tried to slim it down a bit since its a bigger loop with calculation etc. The function itself works fine though.
document.getElementById("test").innerHTML = "post-text";
this part removes your div content, just change it with :
document.getElementById("test").innerHTML += "post-text";
Calc
Full working code:
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
<script>
function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML += "post-text";
}
</script>
And ofcourse you can use element.addEventListener("click", calc)like SimpleJ mentioned.
document.getElementById('button').addEventListener("click", calc);
I copied your code into a file and tried it. Your button doesn't do anything.
Edit: As #SimpleJ stated, calling globally is a bad practice. I updated the answer.
function calc(){
// function body
}
document.getElementById('button').addEventListener("click", calc);
This way the calc() function is actually called when you click the button. It's called adding an EventListener if you need some term to Google for further reference.
I hope this is what you need.

How can I make the height of a div bigger onclick of a button and then change back to it's original height when click again?

I have a div id="coding" set on height:300px on CSS.
when I click another div id="menu", I want #coding to change it's height to 800px. I managed to do that like this
<script>
function changec() {
document.getElementById('coding').style.height = "800px";
}
</script>
Now, when click the #menu again, I want the height to get back to it's original 300px value. Can someone help? The code is:
HTML
<div id="coding">
<div id="menu" onclick="changec()">≡</div>
...
</div>
CSS
#coding{
...
height:300px;
}
Simple check if the value is set - remove it (then CSS height will take over).
function changec() {
var xDiv = document.getElementById('coding');
if (xDiv.style.height == '')
xDiv.style.height = '800px'
else
xDiv.style.height = ''
}
Demo: http://jsfiddle.net/ygalanter/BLE6N/
one of the solution for your problem is as follows:
First count how many times you click on #menu
now depending on your expectation you can change the javascript as follows
<script type="text/javascript">
var count = 0;
function changec() {
count++;
if(count%2==1)
document.getElementById("coding").style.height = "800px";
else
document.getElementById("coding").style.height = "300px";
}
</script>
Another alternative solution is
<script type="text/javascript">
function changec() {
var currentheight = document.getElementById('coding').clientHeight;
if (currentheight == 300)
document.getElementById('coding').style.height = "800px";
else if (currentheight == 800)
document.getElementById('coding').style.height = "300px";
}
</script>
Not sure why you tagged jQuery since you didn't use it, but still...Considering the possibility that you are willing to use/learn it, I created a jsFiddle for it: http://jsfiddle.net/Tm2Hd/.
CSS:
#coding{
border:1px solid black; /*optional: Keep track of your div's expand*/
height:300px;
}
#coding.larger{
height:800px;
}
JS:
function changeHeight() {
if($('#coding.larger').length>0)
{
$('#coding').removeClass("larger");
}
else
{
$('#coding').addClass("larger");
}
}
HTML
<div id="coding">
<!--<div onclick="changeHeight()">≡</div>
Personally, I don't suggest using divs as clickable objects... Why don't you use buttons instead?
-->
<button onclick="changeHeight()">≡</button>
...
</div>
My solution to your problem is: Create a new class named larger, pointing to your div, and toggle between this and the original whenever you click the button.

Event listener not working?

Sorry for so many questions, but I suck at javascript and want to get good at it. I'm trying to make a page change colors when you press a button as another proof of concept for me, but it's not working and I'm not entirely sure why...
<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
button.eventlistener(BGchange, BGcolor());
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
}
else
if(BG==1){
document.body.style.background = black;
}
}
</script>
</body>
</html>
k, fixed a little, here's what I have now:
<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
BGchange.addEventListener("click", BGcolor);
var BG++
function BGcolor (){
if(BG==0){
backgroundcolor = "white";
}
else
if(BG==1){
backgroundcolor = "black";
}
}
</script>
</body>
</html>
If you're trying to listen for an event click, then you need something like this:
document.getElementById("BGchange").addEventListener("click", BGcolor);
Then, you need to fix some things in this function:
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
} else if (BG==1) {
document.body.style.background = black;
}
}
Because you are trying to reference BG2 before it has been initialized so it is not clear what you want to be doing there.
In order, the things I changed:
Get the DOM element for the button with document.getElementById()
Use addEventListener() which is the standard way of adding event handlers
Change to the click event which is what buttons create when you click on them
Pass just a reference to the event handler as BGcolor without the parens. You were calling it immediately rather than passing a reference to the function that can be called later.
In addition, a bunch of things to fix in your BGcolor() function:
Variables that remember their state from one function call to the next must be declared outside that function.
A color value is a string so you would use "white", not white.
To change just the background color, it's best to use the backgroundColor property.
Here's a working version:
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
document.getElementById("BGchange").addEventListener("click", BGcolor);
var curColor = "white";
function BGcolor (){
if (curColor == "white") {
curColor = "black";
} else {
curColor = "white";
}
document.body.style.backgroundColor = curColor;
}
</script>
Working demo: http://jsfiddle.net/jfriend00/Nk2N5/

How to make a function set css width with a JavaScript variable?

I have this code:
...<script>
function handleSize()
{
var setObjectSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setObjectSize + "px";
document.getElementById("spin").style.height=setObjectSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="handleSize()">...
All I am trying to do is to create a function that will set the height and width of the element according to window size using a formula and make sure height and width are the same. I am very new to javascript (almost know nothing about it), so despite there being a ton of example of such questions, and me following them, I can't get this code to work. What am I doing wrong?
The problem that I'm seeing, is that the onload event for the section tag isn't firing. You should add your javascript as a self-executing anonymous function to the end of your body tag and this will work for you.
<body>
<section id="spin" style="border:5px solid black;"></section>
<script>
(function () {
var setWindowSize = window.innerWidth - 600;
document.getElementById("spin").style.width = setWindowSize + "px";
document.getElementById("spin").style.height = setWindowSize + "px";
})();
</script>
</body>
See Here for a demo: http://jsfiddle.net/T7DW6/
You should move onload to the body tag:
<body onLoad="handleSize()">
<section id="spin">...
I would suggest you to use jQuery, that is JavaScript library used world wide. So in order to develop it using jQuery you need to do next
function setElementSize(elId) {
var _w $(window); //to get instance of window
var _el $('#' + elId); //jquery to get instance of element
var _width = _w.width();
var _height = _w.height();
//set width=height
if(_height>_width)
{
_height = _width;
} else { _width = _height; }
_el.css({
width: _width,
height: _height
});
}
//this will execute script when document is loaded.
$(document).ready(function(){
setElementSize('spin');
});
Function above will set width and height of element to match window size. If height > width then it will use width as width & height otherwise it will use height.
I assume that you want to change this automatically if window is resized then do this
$(window).resize(function(){
setElementSize('spin');
});
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
onload is only Supported by the Following HTML Tags:
body, frame, frameset, iframe, img, input type="image", link, script, style
from here: event_onload
then a is may be not the best here (height and weight does not change anything, you should use a div.
In order to know, the one to use, please read this:
what-is-the-difference-between-section-and-div
I try your exam and it works fine. The only thing that i changed was the way that you call the function
function handleSize(){
var setWindowSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setWindowSize + "px";
document.getElementById("spin").style.height=setWindowSize + "px";
}
window.onload = function () {
handleSize();
}
I think that onLoad="handleSize()" have to be onload="handleSize()" but don't use that way because it is not a good practise!
this works for me
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button and watch it grow.</p>
<button id = "myButton" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>
</body>
</html>

How can I change a modal popup every 30 seconds?

I have a div id called modalpage
and have css. I need a javascript function which can dynamically shows popup for 20 mins and change in every 30 secs right now i have the following javascript function. Can anybody help me please
<script language="javascript" type="text/javascript">
function revealModal(divID)
{
window.onscroll = function () {
document.getElementById(divID).style.top = document.body.scrollTop;
};
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
which is called by a input id button.
<input id="Button1" type="button" value="Click here" onclick="revealModal('modalPage')" />
Thanks
This is what i came up with
function revealModal(divID)
{
var i = 1;
divID.replace('*', i);
setInterval(function(){revealModal(divID)},1000);
i = i + 1;
if (i == 3) i = 1;
var div = getElementById(divID)
window.onscroll = function () { document.getElementById(divID).style.top = document.body.scrollTop; };
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
but this is not working its showing the modular_3 every time. is it because of all three divs are in the same file ??
<input id="Button1" type="button" value="Click heres" onclick="revealModal('modalPage_*')" />
Well, for one thing don't put that set interval inside the function. That would start a never ending cycle on the first click that would keep triggering the div id it was passed.
What you should probably do is keep an array of id's that should be updated and loop through that in the function...
var divs = [];
function addID(id)
{
divs.push(id);
}
function revealModal()
{
for(var i = 0; i < divs.length; i ++)
{
var div = getElementById('modalPage_' + divs[i]);
window.onscroll = function () {
div.style.top = document.body.scrollTop;
}
div.style.display = "block";
div.style.top = document.body.scrollTop;
}
}
setInterval(function(){revealModal()},1000);
And your html buttons:
<input id="Button1" type="button" value="Click heres" onclick="addID('1')" />
<input id="Button2" type="button" value="Click heres" onclick="addID('2')" />
<input id="Button3" type="button" value="Click heres" onclick="addID('3')" />
Now consider this - I don't really understand your request. It looks like a bunch of others don't understand either. The way I saw it was you want to reveal a div on click and make sure it updates every nth seconds. In this case, it looks like you chose 1000 ms, or every 1 second even though you said you wanted every 30 seconds. Fair enough, change that 1000 to 30000.
It looks like the ONLY update you do is make sure it sticks to a certain position on the screen and NOT updates the content.
So what I've done is make the interval outside the function so it is always going. Then on click you push the id into the divs array where the interval will update only what is inside the loop. While conceptually this will work, it seems like a bad way to do it.
You should just use an easy library like jquery and place a scroll listener that updates the position whether or not they're revealed. Seeing as you specified jquery in your tags but don't use a lick of it in your example, I assume that means you're not entirely familiar with the library.
This could be done by simply adding a class of "modal" to every modal div and using this:
$(document).ready(function(){
$(window).scroll(function(){
$('.modal').css('top', $(window).scrollTop() + 'px');
});
$('.modal').on('click', function(){
$(this).css('display', 'block');
});
});
Of course you would need to call the jquery library before this call for this to work.

Categories