So I have to make a hidden element (div) visible when you click on an image.
It worked on a button, but I can't seem to make it work on an image.
HTML code:
<div id="img4">
<img src="images/nummer1.png" alt="nummer1" data-hint="1"/>
</div>
<div id="hint" class="hidden">Hint 1</div>
JavaScript code:
window.onload = function () {
'use strict';
var button = document.getElementById("button");
var hint = document.getElementById("hint");
var showHint = function (event) {
console.log(this);
if data-hint === '1'
hint1.classList.toggle('hidden');
};
var img = document.querySelectorAll('img');
console.log(img);
for (var i = 0; i < img.length; i++) {
img[i].addEventListener("click", showHint);
};
function show(hint) {
};
button.addEventListener('click', show);
You see? It works on the button, but for some reason I can't make it work on an Image.
I notice you're not using jQuery. You might want to look into it, as it would make what you're trying to implement easier and much more readable.
But in any event:
hint1.classList.toggle('hidden');
Should be
hint.classList.toggle('hidden');
Also,
if data-hint === '1'
Needs to be
if (this.dataset.hint == 1)
which is how you check the data-hint attribute of this element (the one that was clicked).
http://jsfiddle.net/gunderjt/t46ws/
Should work:
$("img").click(function(){
$("div").show();
});
var showHint = function (event) {
console.log(this);
if(typeOf(hint) != 'null') hint.classList.toggle('hidden');
};
Actually you should update the hints id:s so for every image there are a corresponding hint, which shares the same id. So the first hint got a id of "hint-1".
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<style>
.hidden {
display: none;
}
.show {
display: block;
}
</style>
<div id="img4">
<img src="/test/img2.jpg" alt="nummer1" data-hint="1"/>
</div>
<div id="hint-1" class="hidden">Hint 1</div>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementsByTagName("img");
for(var i=0;i<images.length;i++){
images[i].onclick = function() {
var that = this;
var id = that.getAttribute("data-hint");
var hint = document.getElementById("hint-" + id);
hint.className = "show";
};
}
};
</script>
</body>
</html>
Related
I am trying to make a simple program that allows me to mouse over one image to see another. I am really struggling with how the how to handle the first on mouseover function. I realize imageNode is undeclared, but I don't know where to declare it and what reference it is going to store.
If anyone out there could point me in the right direction to get have image1 replaced with another image in the HTML on mouseover and then return to image1 on mouseout, I would greatly appreciate it. I'm really lost right now.
I have included the HTML as well as the JavaScript below.
Thanks so much,
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
var image1 = $("image1");
var image2 = $("image2");
// preload images
var links = $("image_list").getElementsByTagName("a");
var i,
link,
image;
for ( i = 0; i < links.length; i++) {
link = links[i];
image = new Image();
image.src = link.href;
}
// attach mouseover and mouseout events for each image
image1.onmouseover = function(evt) {
link = this; //this is image that is mouseover
// set new image
//imageNode.src = link.getAttribute("href"
};
image1.onmouseout = function() {
};
image2.onmouseover = function() {
};
image2.onmouseout = function() {
};
};
<!DOCTYPE html>
<html>
<head>
<title>Image Rollover</title>
<link rel="stylesheet" type="text/css" href="rollover.css">
<script type="text/javascript" src="rollover.js"></script>
</head>
<body>
<main>
<h1>Fishing Images</h1>
<p>Move your mouse over an image to change it and back out of the
image to restore the original image.</p>
<ul id="image_list">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<p>
<img id="image1" src="images/hero.jpg" alt="">
<img id="image2" src="images/bison.jpg" alt="">
</p>
</main>
</body>
</html>
one.
If you have some html like <div id="image-rollover"></div>,
you can switch out the image on hover like this using only css:
#image-rollover {
background-color: #000;
background-image: url('SOME_IMG_URL');
background-size: cover;
height: 100px;
width: 100px;
}
#image-rollover:hover {
background-image: url('SOME_OTHER_IMG_URL');
}
Example in JSFiddle
You can do this in Javascript by a simple method:
var imgOnMouseOver = "OVER_IMG_URI";
var imgOnMouseOut = "OUT_IMG_URI";
var container = document.getElementById("IMG_TAG_ID");
container.addEventListener("mouseover", function(){
container.setAttribute("src", imgOnMouseOver);
});
container.addEventListener("mouseout", function(){
container.setAttribute("src", imgOnMouseOut);
});
Example program works fine: https://jsfiddle.net/praveen17/tv8xu67f/2/
image1.onmouseover = function() {
image1.src="images/hero.jpg"
};
image1.onmouseout = function() {
image1.src="images/release.jpg"
};
image2.onmouseover = function() {
image2.src="images/deer.jpg"
};
image2.onmouseout = function() {
image2.src="images/bison.jpg"
};
};
I am trying to swap the src image with the id image. From what I see on other examples I thought this would be the way to go about doing it. It definitely does not work for me. This is my first time posting here so any help with formatting my question would be greatly appreciated also.
HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Rollovers</title>
<link rel="stylesheet" href="main.css">
<script src="rollover.js"></script>
</head>
<body>
<section>
<h1>Image Rollovers</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
</body>
</html>
Javascript:
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//MOUSE EVENT FUNCTIONS
var rollover = function(evt) {
var link = this;
var imageNode = $("img");
imageNode.setAttribute("img", link.getAttribute("id"));
}
var rollout = function(evt) {
var link = this;
var imageNode = $("id");
imageNode.setAttribute("id", link.getAttribute("img"));
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var linkNode = $("image_rollovers");
var images = linkNode.getElementsByTagName("img");
//PROCESS EACH IMAGE
var i, linkNode, image;
for ( i=0; i<images.length; i++)
{
linkNode = images[i];
linkNode.onmouseover = rollover;
linkNode.onmouseout = rollout;
}
}
First, you have a typo in the HTML, you're missing the > at the end of the third <img.
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
^
Second, you're calling $("img") and $("id"), but there are no elements with those IDs. You should just be setting a variable to the appropriate attribute of link. There's no need for different functions for rollover and rollout, since they both just swap the id and src attributes.
//MOUSE EVENT FUNCTIONS
function swap_src_and_id(evt) {
var link = this;
var src = link.getAttribute("src");
link.setAttribute("src", link.getAttribute("id"));
link.setAttribute("id", src);
}
Third, you're calling linkNode.getElementsByTagName("src"), but there's no such tag. It should be img.
window.onload = function () {
//GET ALL IMG TAGS
var linkNode = $("image_rollovers");
var images = linkNode.getElementsByTagName("img");
//PROCESS EACH IMAGE
var i, linkNode, image;
for ( i=0; i<images.length; i++)
{
linkNode = images[i];
linkNode.onmouseover = swap_src_and_id;
linkNode.onmouseout = swap_src_and_id;
}
}
I've got a button with an image inside that I want to swap when clicked. I got that part working, but now I also want it to change back to the original image when clicked again.
The code I'm using:
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
And the Javascript:
function action() {
swapImage('images/image2.png');
};
var swapImage = function(src) {
document.getElementById("ImageButton1").src = src;
}
Thanks in advance!
While you could use a global variable, you don't need to. When you use setAttribute/getAttribute, you add something that appears as an attrib in the HTML. You also need to be aware that adding a global simply adds the variable to the window or the navigator or the document object (I don't remember which).
You can also add it to the object itself (i.e as a variable that isn't visible if the html is viewed, but is visible if you view the html element as an object in the debugger and look at it's properties.)
Here's two alternatives. 1 stores the alternative image in a way that will cause it to visible in the html, the other doesn't.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
var tgt = byId('ImageButton1');
tgt.secondSource = 'images/image2.png';
}
function byId(e){return document.getElementById(e);}
function action()
{
var tgt = byId('ImageButton1');
var tmp = tgt.src;
tgt.src = tgt.secondSource;
tgt.secondSource = tmp;
};
function action2()
{
var tgt = byId('imgBtn1');
var tmp = tgt.src;
tgt.src = tgt.getAttribute('src2');
tgt.setAttribute('src2', tmp);
}
</script>
<style>
</style>
</head>
<body>
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
<br>
<button onClick="action2();">click me<img id='imgBtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>
</body>
</html>
You need to store the old value in a global variable.
For example:
var globalVarPreviousImgSrc;
var swapImage = function(src)
{
var imgBut = document.getElementById("ImageButton1");
globalVarPreviousImgSrc = imgBut.src;
imgBut.src = src;
}
Then in the action method you can check if it was equal to the old value
function action()
{
if(globalVarPreviousImgSrc != 'images/image2.png')
{
swapImage('images/image2.png');
}else{
swapImage(globalVarPreviousImgSrc);
}
}
It's not a good idea to use global variables in javascripts use a closure or object literal. You can do something like using a closure
(function(){
var clickCounter = 0;
var imgSrc1 = "src to first image";
var imgSrc2 = "src to second image"
functions swapImage (src)
{
var imgBut = document.getElementById("ImageButton1");
imgBut.src = src;
}
function action()
{
if(clickCounter === 1)
{
swapImage(imgSrc1);
--clickCounter;
}else{
swapImage(imgSrc2);
++clickCounter;
}
}
})();
(I haven't run this code though)
This nice w3documentation gives you best practices.
Check this a working example just copy paste and run-
HTML
<button onClick="action();">click me<img src="http://dummyimage.com/200x200/000000/fff.gif&text=Image+1" width="200px" id="ImageButton1"></button>
JAVASCRIPT
<script>
function action()
{
if(document.getElementById("ImageButton1").src == 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1' )
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/dec4ce/fff.gif&text=Image+2';
else
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1';
}
</script>
Check this working example - http://jsfiddle.net/QVRUG/4/
I have an icon image which changes into another image by this code
<html>
<script>
function changeImg(thisImg) {
if(prevImg) {
prevImg.src=prevSrc;
}
prevImg = thisImg;
prevSrc = thisImg.src;
thisImg.src = "flag_green.gif";
}
</script>
<body>
<img alt="" src="flag_blue.gif" id="imgClickAndChange" onclick="changeImg(this)" />
</body>
But I am unable to change it back to the previous image again after clicking the original image . please help. I want it similar like the gmail important star icon feature
Why not do it the easy way?
function changeImg(thisImg) {
if(thisImg.src == "flag_green.gif") {
thisImg.src = "flag_blue.gif";
} else {
thisImg.src = "flag_green.gif";
}
}
This might work:
var c = 0;
var images = ['src-for-first-image.jpg','src-for-second-image.jpg'];
$('.trigger').on('click', function() {
$('.image').attr('src', images[c % images.length]);
c++;
});
this lets you loop through many images.
Example:
jsfiddle
Try this: http://jsfiddle.net/pUbrv/
<script>
var altImg = "http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg";
var tmpImg = null;
function changeImg(thisImg) {
tmpImg = thisImg.src;
thisImg.src = altImg;
altImg = tmpImg;
}
</script>
<body>
<img alt="" src="http://www.gettyicons.com/free-icons/136/stars/png/256/star_gold_256.png" id="imgClickAndChange" onclick="changeImg(this)" />
</body>
----------------- EDITED ----------------------
It's probably easier to load both images and toggle the visibility, rather than changing the src of a single img tag.
Try something like this http://jsfiddle.net/qXYGp/:
<span onclick="toggleImg(this)">
<img src="http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg" />
<img src="http://www.gettyicons.com/free-icons/136/stars/png/256/star_gold_256.png" style="display: none"/>
</span>
and for JS:
toggleImg = function(container) {
var imgs = container.getElementsByTagName('img');
for (i in imgs) {
if (imgs[i].style.display == 'none')
imgs[i].style.display = 'inline';
else
imgs[i].style.display = 'none';
}
}
Following is the code which will clone a set of div with their events (onclick) which is working fine for Firefox but in case of IE it is not firing events associated with each div:
<html>
<head>
<style type='text/css'>
.firstdiv{
border:1px solid red;
}
</style>
<script language="JavaScript">
function show_tooltip(idx,condition,ev) {
alert(idx +"=="+condition+"=="+ev);
}
function createCloneNode () {
var cloneObj = document.getElementById("firstdiv").cloneNode(true);
document.getElementById("maindiv").appendChild(cloneObj);
}
function init(){
var mainDiv = document.createElement("div");
mainDiv.id = 'maindiv';
var firstDiv = document.createElement("div");
firstDiv.id ='firstdiv';
firstDiv.className ='firstdiv';
for(var j=0;j<4;j++) {
var summaryDiv = document.createElement("div");
summaryDiv.id = "sDiv"+j
summaryDiv.className ='summaryDiv';
summaryDiv.onmouseover = function() {this.setAttribute("style","text-decoration:underline;cursor:pointer;");}
summaryDiv.onmouseout = function() {this.setAttribute("style","text-decoration:none;");}
summaryDiv.setAttribute("onclick", "show_tooltip("+j+",'view_month',event)");
summaryDiv.innerHTML = 'Div'+j;
firstDiv.appendChild(summaryDiv);
}
mainDiv.appendChild(firstDiv);
var secondDiv = document.createElement("div");
var linkDiv = document.createElement("div");
linkDiv.innerHTML ='create clone of above element';
linkDiv.onclick = function() {
createCloneNode();
}
secondDiv.appendChild(linkDiv);
mainDiv.appendChild(secondDiv);
document.body.appendChild(mainDiv);
}
</script>
</head>
<body>
<script language="JavaScript">
init()
</script>
</body>
</html>
Can anybody tell me what's the problem in above code? Please correct me.
You have multiple problems with your code that make it either not working in some browsers or partial working in others:
onmouseover/onmouseout event
handlers assigned as properties do
not and shall not be copyied when
cloning (in any browser according to DOM specification), that is why you do not see
text-underline effect in any browser
In Internet Explorer (prior to IE9) it is not possible to assign an event handler by setting a onxxx attribute with setAttribute method
You clone an HTML structure with id attributes and insert it into the same document which creates a problem of duplicate id's - this is "illegal" and can lead to unpredictable behavior
So the only solution for you code to start working properly in every browser is to clone fragment without ids and (re-)assign event handlers manually.
I agree with #Sergey Ilinsky. You're running head first into DOM differences between IE and FF.
Try this code, it should help.
<html>
<head>
<style type='text/css'>
.firstdiv{
border:1px solid red;
}
</style>
<script language="JavaScript">
var cloneCount = 0;
var bname = navigator.appName;
var isIE = false;
if (bname == "Microsoft Internet Explorer"){
isIE = true;
}
else{
isIE = false;
}
function show_tooltip(idx,condition,ev) {
alert(idx +"=="+condition+"=="+ev);
}
function createCloneNode () {
var cloneObj = document.getElementById("firstdiv").cloneNode(false);
cloneObj.id += cloneCount++;
createSummaryNodes(cloneObj);
document.getElementById("maindiv").appendChild(cloneObj);
}
function createSummaryNodes(firstDiv){
for(var j=0;j<4;j++) {
var summaryDiv = document.createElement("div");
summaryDiv.id = firstDiv.id+"sDiv"+j
summaryDiv.className ='summaryDiv';
if(isIE){
summaryDiv.onmouseover = function() {this.style.textDecoration="underline";this.style.cursor="pointer";}
summaryDiv.onmouseout = function() {this.style.textDecoration="none";}
summaryDiv.onclick = function() { show_tooltip(j,'view_month',event); };
}
else{
summaryDiv.onmouseover = function() {this.setAttribute("style","text-decoration:underline;cursor:pointer;");}
summaryDiv.onmouseout = function() {this.setAttribute("style","text-decoration:none;");}
summaryDiv.setAttribute("onclick", "show_tooltip("+j+",'view_month',event)");
}
summaryDiv.innerHTML = 'Div'+j;
firstDiv.appendChild(summaryDiv);
}
}
function init(){
var mainDiv = document.createElement("div");
mainDiv.id = 'maindiv';
var firstDiv = document.createElement("div");
firstDiv.id ='firstdiv';
firstDiv.className ='firstdiv';
createSummaryNodes(firstDiv);
mainDiv.appendChild(firstDiv);
var secondDiv = document.createElement("div");
var linkDiv = document.createElement("div");
linkDiv.innerHTML ='create clone of above element';
linkDiv.onclick = function() {
createCloneNode();
}
secondDiv.appendChild(linkDiv);
mainDiv.appendChild(secondDiv);
document.body.appendChild(mainDiv);
}
</script>
</head>
<body>
<script language="JavaScript">
init();
</script>
</body>
</html>
EDIT: I added some VERY basic browser detection, took out the deep copy with cloneNode, restructured some of the code, and added some browser specific code.