Reputation: 350
Using a button, I am trying to make an image move to the top right corner of the page on the first click, and back to it's original position on the second click. Any further clicks will simply continue the cycle, as I am new to JS, I'm not exactly sure what addEventListeners to be using. Thanks in advance
HTML:
<div id="task2" class="task">
<h2>Task 2</h2>
<!-- image courtesy Google Chrome -->
<img src="media/chrome.png" alt="Chrome Browser" id="chrome_browser">
<ol>
<li>First click: Move the Chrome icon to the top, right corner of the page.</li>
<li>Second click: Move the Chrome icon back to it's original spot.</li>
<li>Further clicks: Continue the cycle.</li>
</ol>
<input type="button" value="Move" id="task2control">
</div>
Upvotes: 0
Views: 2111
Reputation: 473
What i did here is unbind the event handler each time you click the button.
$('#task2control').unbind('click').bind('click',setRight);
function setLeft(){
$('#chrome_browser').removeClass('topright');
$('#chrome_browser').addClass('topleft');
$('#task2control').unbind('click').bind('click',setRight);
}
function setRight(){
$('#chrome_browser').removeClass('topleft');
$('#chrome_browser').addClass('topright');
$('#task2control').unbind('click').bind('click',setLeft);
}
Upvotes: 0
Reputation: 12027
This should do the job.
var button = document.getElementById("task2control");
var image = document.getElementById("chrome_browser");
var status = "original";
button.onclick = function () {
switch (status) {
case "topRightCorner":
image.style.position = "";
status = "original";
break;
case "original":
image.style.position = "absolute";
image.style.top = "0";
image.style.right = "0";
status = "topRightCorner";
break;
}
}
Upvotes: 1
Reputation: 169
Is using jquery on your site an option? Then you could have a look at what I came up with.
I added a class to your moving image
<img src="media/chrome.png" alt="Chrome Browser" id="chrome_browser" class="original-pos">
and check for its existance in a simply click event to toggle the position of the div.
$(document).ready(function(){
var originalTop = $('#chrome_browser').css('top');
var originalLeft = $('#chrome_browser').css('left');
$('#task2control').on('click', function(){
var image = $('#chrome_browser');
if(image.hasClass('original-pos')){
image.animate({
top : "0px",
left: "0px"
}, function(){
image.removeClass('original-pos');
});
} else {
image.addClass('original-pos');
image.animate({
top: originalTop,
left: originalLeft
});
}
});
});
Check it out on jsfiddle.
Upvotes: 0