New to Javascript - changing style of element - javascript

So based on the value of a boolean, I want certain tabs in my sidebar to display/ hide when the page loads.
var someVar = true;
function show_ifTrue() {
if (Boolean(someVar) == true) {
document.getElementById('x').style.display = 'block';
console.log("I CHANGED IT");
}
else {
document.getElementById('x').style.background = 'red';
}
}
.sidebar {
position: fixed;
overflow-y: scroll;
top: 0;
bottom: 0;
float: left;
display: inline-block;
z-index: 50;
}
#tab {
display: block;
}
#x {
display: none;
}
<div class="sidebar">
Cats
Dogs
</div>
I have tried everything from taking out the display from .sidebar a{...} and giving each tab its own display property, using !important, changing in JS using style.cssText or setting attribute, I just can't get it to change the display.

In order to change the color, you have to call the function first, but you are never calling it, since onpageshow could only be added to <body>, so you could move it there - <body onpageshow='...'>. Or, if you still want to deal only with the div itself, do it onload:
window.onload=function(){
show_ifTrue();
}
This way too could also use your pageshow:
window.onpageshow=function(){
show_ifTrue();
}
Also, you don't need Boolean prefix in your function, just someVar == true.

It appears that you are missing the css closing braket for #tab (EDIT: OP edited this, but it could also have been part of the issue). Also, you might want to use window.onload, or onpageshow on the body element — it's the only element that it will work on. With that fixed, here's a working example:
window.onload = function () {
show_ifTrue();
}
var someVar = true;
function show_ifTrue() {
if (someVar === true) {
document.getElementById('x').style.display = 'block';
console.log('I CHANGED IT');
}
else {
document.getElementById('x').style.background = 'red';
}
}
.sidebar {
position: fixed;
overflow-y: scroll;
top: 0;
bottom: 0;
float: left;
display: inline-block;
z-index: 50;
}
#tab {
display: block;
}
#x {
display: none;
}
<div class="sidebar">
Cats
Dogs
</div>
I hope that helps!

Related

Jquery Resize Div with Toggle Button

I am building small private projects to learn jquery and currently I am stuck.
The Goal is to click a button and then my menu and my main content area should resize; when I click again it should resize itself back to normal.
The first part does work but the second part "jumps" down - I do not know why.
Here is my JSFiddle: https://jsfiddle.net/ne1mb706/1/
HTML:
<div><button id="show_hide_button">click me</button></div>
<div id="some_box"></div>
<div id="some_other_box"></div>
CSS:
html, body {
margin: 0;
padding: 0;
}
#some_box {
background: #fc0;
width: 25%;
height: 100px;
float:left;
}
#some_other_box {
background: #0cf;
width: 75%;
height: 100px;
float:left;
}
JQuery 3.4.1:
var collapsed = false;
$('#show_hide_button').click(function() {
if(!collapsed){
$('#some_box').animate({width: '0%'});
$('#some_other_box').animate({width: '100%'});
} else {
$('#some_box').animate({width: '25%'});
$('#some_other_box').animate({width: '75%'});
}
collapsed = !collapsed;
});
Thanks for any help :)
You must start with the visible one to animate work properly:
var collapsed = false;
$('#show_hide_button').click(function() {
if(!collapsed){
$('#some_box').animate({width: '0%'});
$('#some_other_box').animate({width: '100%'});
} else {
$('#some_other_box').animate({width: '75%'});
$('#some_box').animate({width: '25%'});
}
collapsed = !collapsed;
});

Sidebar collapses for a second and expands on page load

I have this sidebar which expands or collapses on a button click. Now I've successfully stored it's state in localStorage and it's working fine except there's a slight issue.
When the page loads and there is no state saved in localStorage, the sidebar collapses for a split second and expands. Expand is supposed to be the default state when there is no state stored in localStorage. I don't want it to collapse first and then expand. I just want the page to load with the sidebar expanded.
I have been trying to solve the issue with my own code. But it didn't work then I combined my code with of of SO's posts. It still doesn't work.
Full Code: Codepen
Here's the code(please note that localStorage won't work in SO):
$('document').ready(function() {
if (typeof window.isMinified === "undefined") {
window.isMinified = false;
}
const body = $('#body');
$("#sidebar-toggler").on("click", function () {
if (window.isMinified === false) {
// localStorage.setItem('menu-closed', !$(body).hasClass("sidebar-minified"));
body.removeClass("sidebar-minified-out").addClass("sidebar-minified");
window.isMinified = true;
} else {
// localStorage.setItem('menu-closed', !$(body).hasClass("sidebar-minified"));
body.removeClass("sidebar-minified").addClass("sidebar-minified-out");
window.isMinified = false;
}
});
const state = // localStorage.getItem('menu-closed');
if (state === null) {
$(body).removeClass('sidebar-minified');
} else {
const closed = state === "true" ? true : false;
if (!closed) {
$(body).removeClass('sidebar-minified');
}
}
});
#body {
background: #fff;
transition: all 0.3s;
}
aside.left-sidebar{
background-color: #2c0963;
height: 100vh;
}
.sidebar-minified-out .left-sidebar {
width: 180px;
transition: width .3s ease-in;
}
.sidebar-minified .left-sidebar {
width: 75px;
transition: width .3s ease-in;
}
.sidebar-toggle {
font-weight: 300;
font-size: 15px;
cursor: pointer;
height: 30px;
position: absolute;
left: 20%;
top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="body" class="sidebar-minified sidebar-minified-out">
<aside class="left-sidebar"></aside>
<button id="sidebar-toggler" class="sidebar-toggle">Collapse/Expand</button>
</body>
You can minimize the the flashing effect, by telling the browser to repaint just only one time, in one shot. BUT there will be always one initial size for Your sidebar: the size which has been defined inside Your markup.
In my example, I am using two Observers to track the style and size changes. Please, note the initial sidebar width. You may set the initial sidebar width equal to 0, or let it unassigned, or maybe You can style it the same size as Your expanded sidebar, but there will be always an initial repaint.
Finally, I strongly believe You need to remove the two initial classes from the body.
$(function() {
/* avoid SO unsecure operation error */
var storage = (function () {
return {
setItem: function(k,v){try{return localStorage.setItem(k,v)}catch(e){return !1}},
getItem: function(k){try{return localStorage.getItem(k)}catch(e){return null}}
};
})();
log("jQuery DOM Ready");
$("#sidebar-toggler").on("click", function() {
var isMinified = !$("body").hasClass("sidebar-minified-out");
$("body")
.toggleClass("sidebar-minified", !isMinified)
.toggleClass("sidebar-minified-out", isMinified);
storage.setItem('menu-closed', +!isMinified);
});
var closed = +storage.getItem('menu-closed');
log('Closed: ' + !!closed);
$("body")
.addClass(closed ? "sidebar-minified" : "sidebar-minified-out")
.css({"visibility": "visible"});
});
body {
background: #fff;
transition: all 0.3s;
}
aside.left-sidebar{
background-color: #2c0963;
height: 100vh;
}
.sidebar-minified-out .left-sidebar {
width: 180px;
transition: width .3s ease-in;
}
.sidebar-minified .left-sidebar {
width: 75px;
transition: width .3s ease-in;
}
.sidebar-toggle {
font-weight: 300;
font-size: 15px;
cursor: pointer;
height: 30px;
position: absolute;
left: 20%;
top: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sidebar State</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="visibility: hidden;">
<aside class="left-sidebar"></aside>
<button id="sidebar-toggler" class="sidebar-toggle">Collapse/Expand</button>
<div id="log" style="position:absolute;top:0;right:0;padding:1em;"></div>
<script>
/* only debug functions inside this script block */
function log(msg) {
$("<div>").appendTo("#log").text(msg);
}
var mo = new MutationObserver(function (ml){
for(var m of ml) {
if (m.type == 'attributes') log('Body ' + m.attributeName + ' changed');
}
});
mo.observe(document.getElementsByTagName('body')[0], {attributes: true});
var ro = new ResizeObserver(function (rl){
for(var r of rl) {
var w = r.contentRect.width;
if(w<=75 || w>=180) log('Sidebar width: ' + r.contentRect.width);
}
});
ro.observe(document.getElementsByClassName("left-sidebar")[0]);
</script>
</body>
</html>
EDIT:
If You look at the messages logged by the Observers, You will notice that there is always a repaint, as mentioned above.
After reading this solution of Your previous question: Dark mode flickers a white background for a millisecond on reload I believe You can implement Your Sidebar toggler the same way.
Instead of applying the CSS class to the body, You can apply it to the html. Here is the full code:
HTML
<!DOCTYPE html>
<html>
<head>
<script>
/* Render blocking script */
var c = +localStorage.getItem('menu-closed');
document.documentElement.classList.add(c ? 'sidebar-minified' : 'sidebar-minified-out');
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<aside class="left-sidebar"></aside>
<button id="sidebar-toggler" class="sidebar-toggle">Collapse/Expand</button>
</body>
</html>
JS
$(function() {
$("#sidebar-toggler").on("click", function (e) {
var isMinified = !$("html").hasClass("sidebar-minified-out");
$("html")
.toggleClass("sidebar-minified", !isMinified)
.toggleClass("sidebar-minified-out", isMinified);
localStorage.setItem('menu-closed', +!isMinified);
});
});
Your CSS will remain untouched beside of a small change (I just only removed the #body id).
Now, if You compare the Observed changes, You will notice that the second solution, which is using the blocking JS script in head, is showing only the initial Sidebar size, i.e.: the initial repaint is gone:
1st solution 2nd solution
==============================================================
Sidebar width: 601 Closed: false
jQuery DOM Ready Sidebar width: 180
Closed: false jQuery DOM Ready
Body class changed
Body style changed
Sidebar width: 180
(Credits: Roko C. Buljan):
More information:
The debug functions in my first example are used just only to depict the sequence of the resize and restyle events inside the browser.
Here is some documentation about that Observers:
MutationObserver
ResizeObserver
It is the transition from the css that let the sidebar expand. If you remove the transistion you will see that the sidebar ist immediately expanded on page load. So for the first time you should set CSS classes without transitions.
You could disable the transition via Javascript and enable it again for the click event:
jsfiddle demo
First remove the classes in the body tag:
<body id="body" class="">
<aside class="left-sidebar"></aside>
<button id="sidebar-toggler" class="sidebar-toggle">Collapse/Expand</button>
</body>
Just a few lines to change in the javascript:
$('document').ready(function() {
if (typeof window.isMinified === "undefined") {
window.isMinified = false;
}
const body = $('#body');
$("#sidebar-toggler").on("click", function () {
document.querySelector('.left-sidebar').style.transition = 'inherit';
if (window.isMinified === false) {
localStorage.setItem('menu-closed', !body.hasClass('sidebar-minified'));
body.removeClass('sidebar-minified-out').addClass('sidebar-minified');
window.isMinified = true;
} else {
localStorage.setItem('menu-closed', !body.hasClass('sidebar-minified'));
body.removeClass('sidebar-minified').addClass('sidebar-minified-out');
window.isMinified = false;
}
});
const state = localStorage.getItem('menu-closed');
if (state === null) {
body.addClass('sidebar-minified');
} else {
const closed = state === "true" ? true : false;
if (!closed) {
body.addClass('sidebar-minified-out');
document.querySelector('.left-sidebar').style.transition = 'none';
}
else {
body.addClass('sidebar-minified');
}
}
});
The important changes in above code are two things:
// in the clickevent section: change the transistion to default behaviour
document.querySelector('.left-sidebar').style.transition = 'inherit';
Set the right class depending on state and disable transition:
// ...
if (state === null) {
body.addClass('sidebar-minified');
} else {
// ...
if (!closed) {
body.addClass('sidebar-minified-out');
document.querySelector('.left-sidebar').style.transition = 'none';
}
else {
body.addClass('sidebar-minified');
}
}
*** Update ***
I refactored the code and optimized it a bit. fiddle
HTML:
<body id="body">
<aside class="left-sidebar"></aside>
<button id="sidebar-toggler" class="sidebar-toggle">Collapse/Expand</button>
</body>
CSS:
#body {
background: #fff;
transition: all .3s;
}
aside.left-sidebar {
background-color: #2c0963;
height: 100vh;
width: 75px;
}
.sidebar-minified-out .left-sidebar {
width: 180px;
}
.sidebar-transitions .left-sidebar {
transition: width .3s ease-in;
}
.sidebar-toggle {
font-weight: 300;
font-size: 15px;
cursor: pointer;
height: 30px;
position: absolute;
left: 20%;
top: 0;
}
JS:
$('document').ready(function() {
$("#sidebar-toggler").on("click", function () {
localStorage.setItem('menu-closed', $('#body').hasClass('sidebar-minified-out'));
$('#body').addClass('sidebar-transitions').toggleClass('sidebar-minified-out');
});
localStorage.getItem('menu-closed') === "true" ? $('#body').removeClass('sidebar-minified-out') : $('#body').addClass('sidebar-minified-out');
});
How about moving the animation to a separate class lets say
.sidebar-animated{
transition: width: 0.3s ease-in;
}
and removing it from anywhere else and then adding that class via timeout, so it gets added after the transition is done, you can use useTimeout with 0 seconds, like so,
setTimeout(() => {
$('aside').addClass('sidebar-animated')
},0)
Plus CSS uses Specificity to reach its element, so
.sidebar-minified-out .left-sidebar {
width: 180px;
}
.sidebar-minified .left-sidebar {
width: 75px;
}
Should be changed to this.
.sidebar-minified .left-sidebar {
width: 75px;
}
.sidebar-minified-out .left-sidebar {
width: 180px;
}
because when you have both on the same element, it will take the later because they have the same specificity rule, give it a last shot, thats the last resort for me :D.
thats enough to make it work
https://codepen.io/menawer_cpe/pen/qBZbEdw
here is a working example,
Note: you have an issue with managing state when the sidebar collapsed at first, but thats something related to how you deal with the state.
Why useTimeout with 0? because it pushes the execution to what is called "event loop" making sure it executes after all javascript normal code is executed.
You can try this :
$('document').ready(function() {
if (window.isMinified === undefined) {
window.isMinified = false;
}
const body = $('#body');
$("#sidebar-toggler").on("click", function() {
$('#body .left-sidebar').removeAttr("style");
if (window.isMinified === false) {
body.removeClass("sidebar-minified-out").addClass("sidebar-minified");
window.isMinified = true;
} else {
body.removeClass("sidebar-minified").addClass("sidebar-minified-out");
window.isMinified = false;
}
});
var firstTime = true;
var sidebar = $('#body aside.left-sidebar');
const state = !(null); //localStorage.getItem('menu-closed');
if (state === null) {
$(body).removeClass('sidebar-minified');
} else {
if (firstTime) {
sidebar.css('transition', 'none');
firstTime = false;
}
const closed = state === "true" ? true : false;
if (!closed) {
$(body).removeClass('sidebar-minified');
}
}
});
#body {
background: #fff;
transition: all 0.3s;
}
aside.left-sidebar {
background-color: #2c0963;
height: 100vh;
}
.sidebar-minified-out .left-sidebar {
width: 180px;
transition: width .3s ease-in;
}
.sidebar-minified .left-sidebar {
width: 75px;
transition: width .3s ease-in;
}
.sidebar-toggle {
font-weight: 300;
font-size: 15px;
cursor: pointer;
height: 30px;
position: absolute;
left: 20%;
top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="body" class="sidebar-minified sidebar-minified-out">
<aside class="left-sidebar"></aside>
<button id="sidebar-toggler" class="sidebar-toggle">Collapse/Expand</button>
</body>

Javascript: can't change background on div click or change marginLeft on element

I tried to test changing backgroundColor and marginLeft on this simple example: https://jsfiddle.net/ntqLo6v0/2/
and couldn't make it work.
var collapsed = 0;
$('[data-toggle=collapse-button]').click(function() {
if (collapsed == 0) {
close();
} else {
open();
}
});
function close() {
document.getElementById("button").style.backgroundColor = "blue";
(document.getElementsByClassName("content")[0]).style.marginLeft = "20px";
collapsed = 1;
}
function open() {
document.getElementById("button").style.backgroundColor = "red";
(document.getElementsByClassName("content")[0]).style.marginLeft = "120px";
collapsed = 0;
}
.content {
background-color: green;
width: 200px;
height: 100px;
}
#button {
background-color: red;
width: 100px;
height: 50px;
margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button" data-toggle="collapse-button">
button
</div>
<div class="content">
some content here
</div>
There is just a little issue: $('[data-toggle=collapse-button]').
You are using jQuery but do not define it. That's why you get a Uncaught ReferenceError: $ is not defined in the console.
Here is your updated fiddle where I added jQuery (in the resources left) in order to make your example running.

Is it possible to list multiple ID's in a function, that will not trigger a .hide function?

Got a problem with my slide in menu. Check the my JSfiddle here.
At the moment the slide-in menu closes, whenever clicked on everything else than the menu itself. The problem is, that the menu closes, when i click the text. I would like to perhaps list more ID's inside the same function, something like this;
if(isOpened && e.target.id!='slide-in,text')
My script:
var isOpened = false;
$(document).click(function(e) {
if(isOpened && e.target.id!='slide-in') {
$("#slide-in").removeClass("active");
isOpened = false;
$("#button").show();
} else if(!isOpened && e.target.id=='button'){
$("#slide-in").addClass("active");
isOpened = true;
$("#button").hide;
}
});
Thank you!
You can use an array and indexOf
['slide-in', 'text'].indexOf(e.target.id) === -1
Might I suggest that you add a class to the elements you don't want it to apply to?
!$(this).is('.someClass')
instead of checking for all the ids, check for existence of parent with id as slide-in
if(isOpened && e.target.id!='slide-in') {
if(!$(e.target).parents('#slide-in').length) {
$("#slide-in").removeClass("active");
isOpened = false;
$("#button").show();
}
}
check this fiddle
#slide-in {
position: fixed;
z-index: 10;
top: 0;
width: 300px;
height: 100%;
background-color: #eee;
border-right: 10px solid #ccc;
display:none;
}
and add this inside the .js
$(document).ready(function(){
$("#button").click(function(){
$("#slide-in").show(300);
})
$("#slide-in").click(function(){
$(this).hide(300);
});
});
and if you want more real use this.
in your css change this class like this
#slide-in {
position: fixed;
z-index: 10;
top: 0;
width: 0px;
height: 100%;
background-color: #eee;
border-right: 10px solid #ccc;
display:none;
}
for your js
$(document).ready(function(){
$("#button").click(function(){
$("#slide-in").animate({width: "300px"});
});
$("#slide-in").click(function(){
$(this).animate({width: "0px"});
});
});

Make element move by using Javascript

I am trying to make a webpage where when you click a link, the link moves diagonally every 100 milliseconds.
So I have my Javascript, but right now when I click the link nothing happens
Also, does anyone know of a Javascript IDE I can use to make sure I have no errors in my code?
PS: Does anyone know why my elements dont stretch to fit the whole 200px by 200px of the div element? The links are only small when they should be the same width as their parent div element.
Edited with new advice, although still wont move.
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
var block = null;
var clockStep = null;
var index = 0;
var maxIndex = 6;
var x = 0;
var y = 0;
var timerInterval = 100; // milliseconds
var xPos = null;
var yPos = null;
function moveBlock()
{
if ( index < 0 || index >= maxIndex || block == null || clockStep == null )
{
clearInterval( clockStep );
return;
}
block.style.left = xPos[index] + "px";
block.style.top = yPos[index] + "px";
index++;
}
function onBlockClick( blockID )
{
if ( clockStep != null )
{
return;
}
block = document.getElementById( blockID );
index = 0;
x = parseInt( block.style.left, 10 );
y = parseInt( block.style.top, 10 );
xPos = new Array( x+10, x+20, x+30, x+40, x+50, x+60 );
yPos = new Array( y-10, y-20, y-30, y-40, y-50, y-60 );
clockStep = self.SetInterval( moveBlock(), timerInterval );
}
-->
</script>
<style type="text/css" media="all">
<!--
#import url("styles.css");
#blockMenu { z-index: 0; width: 650px; height: 600px; background-color: blue; padding: 0; }
#block1 { z-index: 30; position: relative; top: 10px; left: 10px; background-color: red; width: 200px; height: 200px;
margin: 0; padding: 0; /* background-image: url("images/block1.png"); */ }
#block2 { z-index: 30; position: relative; top: 50px; left: 220px; background-color: red; width: 200px; height: 200px;
margin: 0; padding: 0; /* background-image: url("images/block1.png"); */ }
#block3 { z-index: 30; position: relative; top: 50px; left: 440px; background-color: red; width: 200px; height: 200px;
margin: 0; padding: 0; /* background-image: url("images/block1.png"); */ }
#block4 { z-index: 30; position: relative; top: 0px; left: 600px; background-color: red; width: 200px; height: 200px;
margin: 0; padding: 0; /* background-image: url("images/block1.png"); */ }
#block1 a { display: block; width: 100%; height: 100%; }
#block2 a { display: block; width: 100%; height: 100%; }
#block3 a { display: block; width: 100%; height: 100%; }
#block4 a { display: block; width: 100%; height: 100%; }
#block1 a:hover { background-color: green; }
#block2 a:hover { background-color: green; }
#block3 a:hover { background-color: green; }
#block4 a:hover { background-color: green; }
#block1 a:active { background-color: yellow; }
#block2 a:active { background-color: yellow; }
#block3 a:active { background-color: yellow; }
#block4 a:active { background-color: yellow; }
-->
</style>
Errors needed to fix
To fill the width of the div elements, the a elements need to be display: block; not their default display: inline;.
Knowing runtime errors is more important in my opinion, and IDEs don't catch DOM errors or anything more complex than syntax; use the error logging in your browser (Firefox's is called Error Console). That'll also catch in-development errors like syntax errors.
This is the most important point to stress: block.style.left and block.style.top are not just numbers with implicit pixel values in them. Setting it to a number without a unit suffix will do absolutely nothing. You need to add % or px or whatever unit when setting left and top.
When getting the current value, as in var x = ... and var y = ..., you need to Number() manually to get the numeric portion of the string.
Also, I believe you meant || block == null, not =, which would set block to null.
Tips
You can use moveBlock instead of "moveBlock();" as an argument to setTimeout. This avoids parsing the string into code, and avoids scope problems (though not in this example as moveBlock is global).
I know that you have an array of values, where both x and y move 10 each time. I assume you want to move at a 45 degree angle. If so, this won't work as you expect even after fixing all the errors as x is percentage and y is in pixels.
You should declare your x and y above like your other variables. It may work but its confusing.
in your setTimeout, use moveBlock, not "moveBlock()" - it will save the step of evaluating your string into code.
block.style.left will return a string that includes "px" - it won't be a number. You can do:
x = Number(x);
//or
x = parseInt(x, 10);
When you set the position, remember to add the "px":
block.style.left = xPos[index] + "px";
EDIT:
Ok, the key problem is 'style.left' is not reading because it was set with CSS and not the style object. I use my library to get the style which runs through a few scenarios and catches that automatically. So change these lines to (this may not be exactly correct but will get things moving):
x = parseInt( node.style.left, 10 ) || 0;
y = parseInt( node.style.top, 10 ) || 0;
Also, this is wrong (you never declared 'self', and you don't need it here anyway; JS is case sensitive, SetInterval is not capped; pass the function, not the function result):
clockStep = self.SetInterval( moveBlock(), timerInterval ); // <-- result of moveBlock
// change to:
clockStep = setInterval( moveBlock, timerInterval ); // <-- the function moveBlock
During dev, you should remove the if() statements that could have been blocking the code and just put a simple count--; in there. It's really hard to debug code when you have literally 20 things wrong. Write a line, test. Write a line, test.
You have HTML comments in the script and style blocks. This is from 1998. While they don't hurt anything intact, in the past I've accidentally edited my code and removed one of them, and this will throw everything out of whack - your IDE, the browser - because they won't know what's wrong and you won't get a good error message.
LANGUAGE="JavaScript" is no longer used and is a waste of bytes.
To help speed development add this line:
window.onloadfunction(){
onBlockClick('block1')
}
That will execute your code right away for testing and you don't have to click every time.
Finally, I highly recommend you use Firefox and Firebug. Developing without it is like trying to build a ship in a bottle with boxing gloves. Using console.log(block.style.left) would have shown you it was not set. The error messages would have told you SetInterval and moveBlock() was incorrect. You do need to remember to remove the console.logs before production though. or... (shameless plug)... use my JavaScript Console Fix library which will do that for you: http://clubajax.org/javascript-console-fix-v2-now-with-ios/

Categories