Reputation: 1873
I'm trying to activate a CSS transition with Javascript through DOM when a div object is clicked. I avoided jQuery and used JS on purpose in order to learn DOM (this is actually my first experiment with it). I implemented a standard solution: getting the elements' ListNode from the HTML document, then changing the className of the desired object. Yet, it does not seem to work properly (I'm obviously using Firefox).
Thank you in advance.
Here are the files.
<!doctype html>
<html>
<head>
<link rel = stylesheet href = "style.css" type = "text/css" media = screen>
<script src = "script.js" type = "text/javascript"></script>
</head>
<body>
<div class = "image" onclick = "foo()"></div>
</body>
</html>
style.css
.transition {
-moz-transition: 2s width;
width: 150px;
height: 100px;
}
.image {
-moz-transition: 2s width;
width: 100px;
height: 100px;
background-color: black;
}
script.js
function foo() {
var k = document.getElementsByClassName("image");
k[0].className = "transition";
}
EDIT: Edited the code in order to make immediately visible the working solution.
Upvotes: 1
Views: 777
Reputation: 3200
As Stencil mentioned everything should be inside HTML Tag.Similar kind of width animation could be easily achieved using jQUery
$('.image').animate({width: 250}, 500 );
Upvotes: 1
Reputation: 14187
Try this in your javascript logic:
function foo() {
var k = document.getElementsByClassName("image");
k[0].className = "transition";
}
Upvotes: 1
Reputation: 25766
You're using getElementsByName
, but you don't have an element with a name of image
, instead you have an element with a class of image
. You probably intended to use document.getElementsByClassName('image')
. On a side note, the structure of your html page is incomplete, you need a <head>
and <body>
section, also your <html>
opening tag is in the wrong place.
<!doctype html>
<html>
<head>
<link rel = stylesheet href = "style.css" type = "text/css" media = screen>
<script src = "script.js" type = "text/javascript"></script>
</head>
<body>
<div class = "image" onclick = "foo()"></div>
</body>
</html>
Upvotes: 2