Javascript ID reassignment - javascript

I am working on a project, and I want to make 4 images move in a circular fashion once I click on one of them. This is what I have so far, but I can't figure out how to make the circle keep going. Any help?
<!DOCTYPE html>
<html>
<head>
<title> Lab 13B </title>
<style>
#pic1 {
padding-left:325px;
}
#pic2 {
padding-top: 100px;
}
#pic3 {
padding-left: 350px;
padding-top: 100px;
}
#pic4 {
padding-left: 325px;
padding-top: 120px;
}
</style>
<script>
function one() {
document.getElementById("pic1").src = "water.PNG";
document.getElementById("pic2").src = "fire.PNG";
document.getElementById("pic3").src = "Air.PNG";
document.getElementById("pic4").src = "earth.PNG";
document.getElementById("pic1").id = "pic2";
document.getElementById("pic2").id = "pic4";
document.getElementById("pic3").id = "pic1";
document.getElementById("pic4").id = "pic3";
}
</script>
</head>
<body>
<img src = "Air.PNG" alt="air" width="300px" height="300px" id="pic1" onclick="one()";> <br>
<img src = "water.PNG" alt="water" width="300px" height="300px" id="pic2" onclick="one()";>
<img src = "earth.PNG" alt="earth" width="300px" height="300px" id='pic3' onclick="one()";> <br>
<img src = "fire.PNG" alt="fire" width="300px" height="300px" id='pic4' onclick="one()";>
</body>
</html>

You are essentially talking about an animation where you need to change something around after specific time interval.
To achieve things like that Javascript provides setInterval function where you can run a piece of code responsible for "change" after given interval in milliseconds. So your function one will look something like
function one() {
setInterval(function() {
// your logic for swapping src of images
}, 1000)
}
But this will require you to properly handle click event, first click will start the animation but second will create the interval again and so on, so considering this if you already have interval running then on second click you might want to stop the animation or at least prevent the creation of second interval. This might be of some help Is there any way to kill a setInterval loop through an Onclick button

Related

How to make an onclick function change the src for two images

I'm supposed to add script to an HTML file so that when I click the first star in the star rating system, it will change the src to 'star-on.png' as opposed to 'star-off.png'. That, I can do. But I can't figure out how to make it so that if the user clicks the second star, it will change the src for both the first and the second star to 'star-on.png'.
Here's the code that my teacher provided:
<!-- 1. PUT YOUR NAME IN THIS COMMENT -->
<html>
<head>
<!-- 2. DO NOT EDIT THE CSS -->
<style type="text/css">
body {
margin: 0;
}
div {
width: 520px;
display: block;
margin-left: auto;
margin-right: auto;
}
img {
width: 100px;
}
</style>
<!-- 2.5 YOU MAY ALTER THE STYLING OF THE BUTTON IF YOU WISH. -->
<style type="text/css">
button {
width: 200px;
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<!-- 3. DO NOT ALTER THE HTML EXCEPT TO ADD ONCLICK, ONLOAD, AND SIMILAR ATTRIBUTES -->
<!-- AS NEEDED -->
<body>
<div>
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
<img src="star-off.png" id="three">
<img src="star-off.png" id="four">
<img src="star-off.png" id="five">
</div>
<button id="reset" onclick="document.getElementById('one').src='star-off.png'">Reset</button>
<!-- 4. YOU MAY PUT YOUR SCRIPTING HERE -->
<script>
document.getElementById('one').onclick = function () {
document.getElementById('one').src="star-on.png";
}
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
document.getElementById('three').onclick = function () {
document.getElementById('three').src="star-on.png";
}
document.getElementById('four').onclick = function () {
document.getElementById('four').src="star-on.png";
}
document.getElementById('five').onclick = function () {
document.getElementById('five').src="star-on.png";
}
</script>
</body>
</html>
Except for the things inside the script tag and the onclick inside of the button, it's all my teacher's code.
This is what it looks like:
Well, you've really got most of what you're trying to do in your script already. Look at each of these lines:
document.getElementById('one').onclick = function () {
document.getElementById('one').src="star-on.png";
}
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
document.getElementById('three').onclick = function () {
document.getElementById('three').src="star-on.png";
}
document.getElementById('four').onclick = function () {
document.getElementById('four').src="star-on.png";
}
document.getElementById('five').onclick = function () {
document.getElementById('five').src="star-on.png";
}
Essentially, each one is saying select the element by its Id attribute, identified in the preceding group by the 'id=""' in this part:
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
<img src="star-off.png" id="three">
<img src="star-off.png" id="four">
<img src="star-off.png" id="five">
and then attach an onclick event to it. When that onclick event fires, do the function that you've defined to the right of each of the equal signs following the event specification.
Inside each of your functions, it is simply going to identify the element on the DOM that matches the element id you're providing (just as you already did to assign the event handler in the previous section) and you're going to change the value for its 'src' attribute to the string you're defining on the right side of the equals.
Take the second one, per your request. Here's the HTML you're referencing (for both the first and second stars):
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
And here is the event handler you've already got in place for the second one:
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
Right now if you click on that second star, you're only changing the src attribute of the element with an ID of 'two' to the 'star-on.png' image. So, if you want to also change the element of the star before it, it's got an ID of 'one', so you'll need to add this line within the event handler.
document.getElementById('one').src = "star-on.png";
Sure, there are more efficient ways to do this, but undoubtedly you'll learn about them as your course progresses. Here's what your event handler will look like with this update:
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
document.getElementById('one').src = "star-on.png";
}

I want my animation to travel horizontally across the screen and stop once i press the stop button

I want to make a couple things happen here:
Start button starts the animation and then turns into Stop button.
Stop button then stops animation where it is and turns back into Start button and enables me to resume from where it stopped.
Instead the animation just disappears once i press start or stop again.
I am a newbie when it comes to this kind of stuff, if I am not clear in my intent please tell me so, and I will try to clear it up as best as I can.
<html>
<head>
<meta charset="UTF-8">
<style>
div {left: 0px;
bottom: 100px;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
move();
Stop();
});
function move(){
$("input").click(function(){
$(this).val('Stop');
$("div").css({left:'0%'}).animate({left:'100%'},1000, Stop);
Stop();
});
}
function Stop(){
$("input[value='Stop']").click(function(){
$( ":animated" ).stop(true, true, false);
$(this).val('Start');
move();
});
}
</script>
</head>
<body>
<h1 style="text-align:center"> Welcome to the test</h1>
<input type='button' value='Start' id='oneButton'>
<div style="height:100px;width:100px;position:absolute;">
<img id='myRobot' src='myRobot.jpg' width="250px" height="200px"/>
</div>
</body>
</html>
Your JavaScript code is a little bit messy. First of all your move function:
function move(){
$("input").click(function(){
$(this).val('Stop');
$("div").css({left:'0%'}).animate({left:'100%'},1000, Stop);
Stop();
});
}
Your Stop function (not the one set as callback function of the animate function) will be called while the div is animated. You don't want this.
What you might wants is essentially three different functions:
move
pause
reset
Your move function will essentially start to move your object, the pause will obviously pause it, while the reset will put your object in the initial position, if you wanto so.
Let say your HTML file is structured like this:
<h1 style="text-align:center"> Welcome to the test</h1>
<input type='button' value='Start' id='oneButton' />
<div id="object">
<img id='myRobot' alt='test' src='http://www.clker.com/cliparts/7/b/d/b/1237099752389782475nicubunu_Soccer_ball.svg.thumb.png'/>
</div>
Your CSS:
#object {
position: absolute;
left: 0px;
bottom: 100px;
width: 100px;
height: 100px;
}
And finally the JS:
var animating = false;
$("#oneButton").on("click", function() {
if (!animating) {
$(this).val("pause");
move();
} else {
$(this).val("start");
pause();
}
});
function move() {
animating = true;
$("#object").animate({left:'100%'},1000, reset);
}
function pause() {
$("#object").stop();
animating = false;
}
function reset() {
animating = false;
$("#object").css({left: '0%'});
}
Here is a FIDDLE where you can seet in "action".

Multiple image rollover in javascript with for loop

Please help me. I want to do the below activity in javascript programming with the help of "for loop".
Suppose there are five images on the web page. When I rollover the 1st image, the text should display "it's a first image". When I rollover the 2nd image, the text should display "it's a second image". When I rollover the 3rd image, the text should display it's a third image.
I have tried and it's successful but it's manual. I am new in Javascript programming..
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<link rel="stylesheet" href="style_latest.css" type="text/css">
<title>MATHERAN TRIP</title>
<style>
#displayText
{
width:413px;
height:auto;
background-color:#666666;
color:white;
}
#displayText1
{
padding-left:5px;
}
</style>
</head>
<body>
<img src="images/img1.jpg" id="img1" onmouseover="clickEvent1()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img2.jpg" id="img2" onmouseover="clickEvent2()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img3.jpg" id="img3" onmouseover="clickEvent3()" onmouseout="imgRollout()" width="100" height="100">
<img src="images/img4.jpg" id="img4" onmouseover="clickEvent4()" onmouseout="imgRollout()" width="100" height="100"><br/>
<div id="displayText">
<span id="displayText1"></span>
</div>
<script>
var myData=new Array("Hi, How r u?", "Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up? Hey, whats up?", "Hello, whats going on?", "Hi friends")
document.getElementById("displayText").style.visibility='hidden';
function clickEvent1()
{
document.getElementById("displayText1").innerHTML=myData[0];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent2()
{
document.getElementById("displayText1").innerHTML=myData[1];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent3()
{
document.getElementById("displayText1").innerHTML=myData[2];
document.getElementById("displayText").style.visibility='visible';
}
function clickEvent4()
{
document.getElementById("displayText1").innerHTML=myData[3];
document.getElementById("displayText").style.visibility='visible';
}
function imgRollout()
{
document.getElementById("displayText").style.visibility='hidden';
}
</script>
</body>
</html>
I would recommend you don't include inline event attributes at each element. But I would consider including an inline html5 data- attribute with the message associated with the elements:
<img src="images/img1.jpg" data-msg="Hi, How r u?" width="100" height="100">
<!-- etc -->
Then you can bind the same rollover functions to each element using a loop as follows:
function doMouseOver(e) {
document.getElementById("displayText1").innerHTML =
e.target.getAttribute("data-msg");
document.getElementById("displayText").style.visibility='visible';
}
function doMouseOut() {
document.getElementById("displayText").style.visibility='hidden';
}
var imgs = document.getElementsByTagName("img"),
i;
for (i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("mouseover", doMouseOver);
imgs[i].addEventListener("mouseout", doMouseOut);
}
Within the doMouseOver() function, the e argument is the event object, and thus e.target gives you a reference to the element the event happened to - so then you can retrieve the particular data-msg value for that element to display it.
Demo: http://jsfiddle.net/3c7Rb/
Having said that, you don't need the loop either. You can bind the functions directly to the document, and then within the mouse over handler you simply test whether the target element has the msg-data attribute. If it does, display it, otherwise do nothing:
function doMouseOver(e) {
var msg = e.target.getAttribute("data-msg");
if (msg) {
document.getElementById("displayText1").innerHTML= msg;
document.getElementById("displayText").style.visibility='visible';
}
}
function doMouseOut() {
document.getElementById("displayText").style.visibility='hidden';
}
document.addEventListener("mouseover", doMouseOver);
document.addEventListener("mouseout", doMouseOut);
Demo: http://jsfiddle.net/3c7Rb/1/

Onmouseover OnMouseout javascript

I wrote a script which changes the source of an image upon mouse over the image,
at first it worked, but after adding a second image which uses the same code both stopped working.
The issue I am experiencing is that the image does not change on mouse over as it should. It looks as if the image is not found – however I am really sure the images' sources point to the right path.
I have asked for other opinions as well and I cannot see what I am doing wrong. I would really appreciate your help or any input on this.
Below is the code I am using.
<html>
<head>
<script type="text/javascript">
var images= new Array();
images[0] = "Benjamin/Untitled-3.png";
images[1] = "Benjamin/Untitled-4.png";
images[2] = "Benjamin/Update.png";
images[3] = "Benjamin/Update2.png";
function Change()
{
document.getElementById("image").src = images[1];
}
function GoBack()
{
document.getElementById("image").src = images[0];
}
function GobackAgain()
{
document.GetElementById("Update").src = images[2];
}
function ChangeAgain()
{
document.getElementById("Update").src = images[3];
}
</script>
<style type="text/css">
body
{
background-color:#1c1a1a;
}
</style>
<div align="center">
<img src="Untitled-2.png" width="325" height="191">
</div>
</head>
<body>
<img onmouseover="Change()"
onmouseout="GoBack()"
id="image"
STYLE="position:absolute; TOP:35%; LEFT:10%; WIDTH:204px; HEIGHT:278px"
src="Untitled-3.png">
<img onmouseover="ChangeAgain()"
onmouseout="GoBackAgain()"
id="Update"
STYLE="position:absolute; TOP:35%; LEFT:50%; WIDTH:204px; HEIGHT:278px"
src="Update.png">
</body>
</html>
Rename GobackAgain to GoBackAgain and replace GetElementById with getElementById.
Here is one problems:
function GobackAgain()
{
document.GetElementById("Update").src = images[2];
}
You have GetElementById when it should be getElementById

Get image src from a image in a slideshow

I've been looking around much today and spend a few hours trying to get something done. For a client I am creating a slideshow with a lightbox when clicked on an image. The slideshow and lightbox both work, but I don't get the right image in the lightbox yet.
This is the code that loads the slideshow and when clicked on an image opens the lightbox.
(The images for the slideshow get loaded by a php script and turned into a Javascript array)
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
}
</script>
<div style="width: 170px; height: 160px">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style. display='block'">
<img id="slideshow" src="" />
</a>
<div id="light" class="white_content">
<img id="lightImg" src="" />
<script>
var image = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", image);
</script>
I now try to create a variable named "image"and let this contain the src of the current image in the slideshow. So I can load this to the image in the lightbox.
Hopefully some one can give me some usefull tips. I am pretty new in the Javascript language.
The script for the slideshow came from: http://www.javascriptkit.com/javatutors/externalphp2.shtml
Regards Koen.
These days there really is no excuse for using obtrusive Javascript (Stuff inside your HTML attributes, ideally it should be in an external file. http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
I have done you the favour of cleaning up your code a bit, and changed it where you seemed to be going wrong. As DotNetter has already pointed out it would be sensible to use jQuery in this instance, as it really does simplify things. However, I'm going to assume that for some reason you want it in plain js. Below is a simplification of the code that you posted with the correct change.
<style type="text/css">
.wrapper {
width: 170px;
height: 160px;
}
</style>
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/" + galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
</script>
<div class='wrapper'>
<img id="slideshow" src="" />
<div id="light" class="white_content">
<img id="lightImg" src="" />
</div>
</div>
Before, you were getting the src of the current image when the page loaded, you need to be getting the src of the image when the user clicks on the

Categories