j singh j singh - 7 months ago 36
HTML Question

Javascript not doing it's job

As you may know, I'm very new to HTML and JS.
I tried to make an image move when you click on it, but for a some reason it doesn't work. Can someone take a look at it?
(It's my first day of learning Javascript! Please keep this in mind)

Javascript

var main = function() {
$('document.Image').click(function() {
$(this).animate({
left: "100px"
}, 200);
});

};


HTML

<html>
<head>
<title>JS Test</title>
</head>
<body>
<img height="25px" width="25px" src="https://webdesignfromscratch.com/snippets/html-css-javascript.gif">
<script type="text/javascript" src="app.js"></script>
</body>
</html>

Answer
  • You need to invoke/call main function
  • documemt.Image was invalid selector. Give class as .image to element which can be selected using $('.image')
  • To apply left css property in .animate(), element must be absolute/relative/fixed positioned. Review the updated css

var main = function() {
  $('.image').click(function() {
    $(this).animate({
      left: "100px"
    }, 200);
  });
};
main();
.image {
  position: absolute;
  left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img class='image' height="25px" width="25px" src="https://webdesignfromscratch.com/snippets/html-css-javascript.gif">