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/
Related
This question already has answers here:
How to Call a JS function using OnClick event [duplicate]
(7 answers)
Closed 10 months ago.
I am trying to make it so when you click on each image in the html you recieve an alert telling you what each picture is.
<html lang="en">
<head>
<title>Task 2</title>
</head>
<body>
<img id="blackcircle" src="31NXhN9iZoL._AC_SY355_.jpg" height="200" width="250"
onMouseClick="eventOne()"/>
<img id="redtriangle"src="1200px-Red_triangle_with_thick_white_border.svg.png"
height="200" width="250" onMouseClick="eventTwo()"/>
<img id="bluesquare"src="download.png" id="jamaica" height="200" width="250"
onMouseClick="eventThree()"/>
<script>
var myImages = [
"31NXhN9iZoL._AC_SY355_.jpg",
"1200px-Red_triangle_with_thick_white_border.svg.png",
"download.png",
];
function eventOne()
{
alert("You have clicked on the black circle");
}
function eventTwo()
{
alert("You have clicked on the red triangle");
}
function eventThree()
{
alert("You have clicked on the blue square");
}
</script>
</body>
The images I used were just random ones I pulled from the web but did not go back in to rename them yet.
The event handler is called onclick not onMouseClick.
function eventOne() {
alert('You have clicked on the black square');
}
function eventTwo() {
alert('You have clicked on the red square');
}
function eventThree() {
alert('You have clicked on the blue square');
}
<img src="https://dummyimage.com/100x100/000/fff" onclick="eventOne()" />
<img src="https://dummyimage.com/100x100/ff0000/000" onclick="eventTwo()" />
<img src="https://dummyimage.com/100x100/0000ff/000" onclick="eventThree()" />
I changed a little your code and tested it here.
Try it now like this:
<html lang="en">
<head>
<script>
var myImages = [
"31NXhN9iZoL._AC_SY355_.jpg",
"1200px-Red_triangle_with_thick_white_border.svg.png",
"download.png",
];
function eventOne()
{
alert("You have clicked on the black circle");
}
function eventTwo()
{
alert("You have clicked on the red triangle");
}
function eventThree()
{
alert("You have clicked on the blue square");
}
</script>
<title>Task 2</title>
</head>
<body>
<img id="blackcircle" src="31NXhN9iZoL._AC_SY355_.jpg" height="200" width="250" onclick ="eventOne()"/>
<img id="redtriangle"src="1200px-Red_triangle_with_thick_white_border.svg.png" height="200" width="250" onmouseup="eventTwo()"/>
<img id="bluesquare" src="download.png" height="200" width="250" onclick="eventThree()"/>
</body>
The mouseup event fires when the user releases the mouse button.
I am new to JavaScript. I created this code in order to try and make buttons that will hide
and show certain pictures on the page. I have 3 buttons, the first of which is supposed to run my JavaScript code in <script></script> tags, the other two just have Javascript code inside them and they work fine. But they don't hide the picture once they are clicked a second time, which is why I am trying to do that for the first one if possible.
For some reason, I cannot get the first button with "open()" to work the way I want with my Javascript code. Can anyone with more experience please explain to me what I am doing wrong? Thank you in advance...
var btn1 = document.getElementById('1');
var btn2 = document.getElementById('2');
var btn3 = document.getElementById('3');
var display1 = btn1.getAttribute('display')
var display2 = btn2.getAttribute('display')
var display3 = btn3.getAttribute('display')
function open() {
if (display1 === ('none')) {
btn1.setAttribute('display', 'block');
} else {
btn1.setAttribute('display', 'none');
}
}
<img id="1" src="forge.PNG" style="height:320px; display:none; padding:10px">
<img id="2" src="lizard.jpg" style="height:320px; display:none; padding:10px">
<img id="3" src="walkway.jpg" style="height:320px; display:none; padding:10px">
<button onclick="open()">1</button>
<button onclick="document.getElementById('2').style.display='block'">2</button>
<button onclick="document.getElementById('3').style.display='block'">3</button>
I'd use event delegation to watch for clicks on the container. When the nth button is clicked, select the nth image, and toggle a class that hides/shows the image:
const images = document.querySelectorAll('img');
const buttons = [...document.querySelectorAll('button')];
document.addEventListener('click', (e) => {
if (e.target.matches('button')) {
const i = buttons.indexOf(e.target);
images[i].classList.toggle('hidden');
}
});
.hidden {
display: none;
}
<img id="1" src="https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="2" src="https://www.gravatar.com/avatar/978ec0c47934c4b04401a8f4b4fec8bd?s=32&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="3" src="https://lh3.googleusercontent.com/-uIr21N5ccCk/AAAAAAAAAAI/AAAAAAAAHeg/ohNEkpJKXQA/photo.jpg?sz=32" style="height:320px; padding:10px" class="hidden">
<button>1</button>
<button>2</button>
<button>3</button>
Problems with your original code include:
You're trying to select the elements before they exist in the DOM
Elements do not have a display property - in order to check the style of an element, you have to access its .style property first (eg, someImage.style.display)
Similarly, to set the style of an element, you have to set a property of its style property (eg someImage.style.display = <newDisplay>). Setting the display attribute of the element won't do anything.
Try to avoid inline handlers if at all possible - they have many problems and are pretty much universally considered to be quite poor practice. Always attach listeners properly using Javascript instead, whenever that's an option.
The event listener is the better solution, but if you want to see a working code in your way:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switchpics</title>
</head>
<script type="text/javascript">
var open = function(param) {
img = document.getElementById(param.innerHTML);
if (img.style.display == 'none'){
img.style.display = "block";
} else {
img.style.display = "none";
};
};
</script>
<body>
<img id="1" src="1.jpg" style="height:20px; display:block; padding:10px">
<img id="2" src="1.jpg" style="height:20px; display:none; padding:10px">
<img id="3" src="1.jpg" style="height:20px; display:none; padding:10px">
<button onclick="open(this)">1</button>
<button onclick="open(this)">2</button>
<button onclick="open(this)">3</button>
</body>
</html>
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
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
I have a function, used to clone the flash article scroller this page. Unfortunately I'm behind a firewall so can't upload my own code, but that should give you an idea. The function:
function select(id) {
alert(active+"\n"+((active+1)%4));
var prev = active;
active = (typeof(id) == "undefined" ? (active+1)%4 : id);
$("#panel").animate({"top": tops[active]}, 750);
$("#main"+prev).fadeOut(750);
$("#main"+active).fadeIn(750);
}
So if select() is called without an id, it simply progresses to the next item in sequence, otherwise it goes to the selected item. It's run on a timer defined:
timer = setInterval("select()", 5000);
When an object is mouseovered, this function is run:
$("img.thumb").mouseover(function() {
clearInterval(timer);
select($(this).attr("id").substr(-1));
timer = setInterval("select()", 5000);
});
The trouble is that, after a mouseover, the select function fails for one cycle, with the next object having no relation to the previous. The chosen object is consistent - it remains the same with each refresh given the same initial conditions, but it's unrelated in any way I can determine.
What is oddest is that the alert I run at the start of select(), which should be a straightforward mathematical operation, fails, claiming that (for the sequence I test - wait for an automatic scroll from 0 - 1, then mouseover 3) (3+1)%4=3.
I've tested this in both firefox and chrome, so it seems to be inherent to javascript.
I can only assume that it's storing two different values for active somehow, but nature of that schism, and how to resolve it, are beyond me.
I've attached the entire file below in case anything else is pertinent. Seems unlikely, but at this point I'm not ruling anything out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="imagetoolbar" content="no" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//alter these as you please
var thumbs = ["images/1t.png", "images/2t.png",
"images/3t.png", "images/4t.png"];
var mains = ["images/1.png", "images/2.png",
"images/3.png", "images/4.png"];
var links = ["http://www.goldcoast.com.au/gold-coast-beaches.html",
"http://www.goldcoast.com.au/gold-coast-whale-watching.html",
"http://www.goldcoast.com.au/gold-coast-hinterland-rainforest.html",
"http://www.goldcoast.com.au/gold-coast-history.html"];
//don't touch these
var timer = null;
var active = 0;
var tops = [0, 77, 155, 234];
function select(id) {
alert(active+"\n"+((active+1)%4));
var prev = active;
active = (typeof(id) == "undefined" ? (active+1)%4 : id);
$("#panel").animate({"top": tops[active]}, 750);
$("#main"+prev).fadeOut(750);
$("#main"+active).fadeIn(750);
}
$(function() {
for(var i = 0; i < 4; i++) {
$("#thumb"+i).attr("src", thumbs[i]);
$("#main"+i).attr("src", mains[i]);
}
$("#main"+active).show();
$("img.thumb").mouseover(function() {
clearInterval(timer);
select($(this).attr("id").substr(-1));
timer = setInterval("select()", 5000);
});
timer = setInterval("select()", 5000);
});
</script>
<style type="text/css">
#container {position:relative;}
#panel {position:absolute;left:0px;top:0px;z-index:1;}
img.thumb {position:absolute;left:8px;z-index:2;}
#thumb0 {top:7px;}
#thumb1 {top:84px;}
#thumb2 {top:162px;}
#thumb3 {top:241px;}
img.main {position:absolute;left:118px;top:2px;display:none;}
</style>
</head>
<body>
<div id="container">
<img src="images/panel.png" id="panel" />
<img id="thumb0" class="thumb" />
<img id="thumb1" class="thumb" />
<img id="thumb2" class="thumb" />
<img id="thumb3" class="thumb" />
<img id="main0" class="main" />
<img id="main1" class="main" />
<img id="main2" class="main" />
<img id="main3" class="main" />
</div>
</body>
</html>
Use parseInt() as comment suggested.