Assigning element attribute to an other element's innerhtml. Javascript/HTML - javascript

I'm working on a website, and the pictures page I'm trying to create has 1 big picture, with smaller thumbnails underneath. I have a javascript function in the head:
function loadThumbnail(divID){
document.getElementById("mainPicture").src = document.getElementById(divID).src;
document.getElementById("mainPicture").alt = document.getElementById(divId).alt;
document.getElementById("caption").innerHTML = document.getElementById(divId).alt;
}
The parameter divID is a misleading title, it's actually the ID of the img element that holds the thumbnail. The function is called whenever the user clicks a thumbnail. The .src bit works, but I can't get the function to change the caption to the picture. Any idea why?
Edit: Here's the HTML
<img id="mainPicture" src="images/food/chickenAndCheeseFries1.png" width="420" height="313" alt="Chicken Tenders and Cheese Fries">
<p id="caption">Chicken tenders and cheese fries</p>
<div onClick="loadThumbnail('t1')" id="thumbnail1" class="thumbnail">
<div id="thumbnailPic1" class="thumbnailPic">
<img id="t1" src="images/food/buffaloAndHotWings1.png" width="105" height="80" alt="Sweet Chilly and Buffalo Wings">
</div>
</div>

Make sure the divID variable is used consistently, including the case. It looks like you typoed and used "divId", which won't work. Try it like this, "divID", in all cases.
function loadThumbnail(divID) {
document.getElementById("mainPicture").src = document.getElementById(divID).src;
document.getElementById("mainPicture").alt = document.getElementById(divID).alt;
document.getElementById("caption").innerHTML = document.getElementById(divID).alt;
}
Case matters! divID != divId

Related

JavaScript event handler click thumbnail to enlarge image

So I am very new to Web Design and am having issues getting my click event handler to work.I cant change the html or css files. My task is to set a click handler to my thumbnails to enlarge the image in the img within the <figure> element. While also setting the figcaption text in the figure to the thumbs title attribute. I need to attach to the div id = thumbnails. My script is not enlarging my thumbnails or titles.
This is my created HTML Doc:
<!DOCTYPE html>
<html lang="en">
<head >
<meta charset="utf-8">
<title>Chapter 9 - Share Your Travels</title>
<link rel="stylesheet" href="css/styles.css" />
<script type="text/javascript" src="js/chapter09-project02.js">
</script>
` `</head>
<body>
<header>
<h2>Share Your Travels</h2>
<nav><img src="images/menu.png"></nav>
</header>
<main>
<figure id="featured">
<img src="images/medium/5855774224.jpg" title="Battle" />
<figcaption>Battle</figcaption>
</figure>
<div id="thumbnails">
<img src="images/small/5855774224.jpg" title="Battle"/>
<img src="images/small/5856697109.jpg" title="Luneburg"/>
<img src="images/small/6119130918.jpg" title="Bermuda" />
<img src="images/small/8711645510.jpg" title="Athens" />
<img src="images/small/9504449928.jpg" title="Florence" />
</div>
</main>
</body>
</html>
Js script:
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == 'img') {
var clickedImageSource = e.target.src;
var newSrc = clickedImageSource.replace("small", "medium");
var featuredImage = document.querySelector("#featured img");
featuredImage.src = newSrc;
featuredImage.title = e.target.title;
}
});
var img = document.getElementById("figcaption");
img.addEventListener("mouseover",function (event) {
img.className = "featured figcaption";
});
img.addEventListener("mouseout", function (event) {
img.className = "featured figcaption";
var element = document.getElementById('figcaption');
element.style.opacity = "0.9";
element.style.filter = 'alpha(opacity=0%)';
});
Thanks for any advice and hopefully I can pay it forward for someone else!
I think it causes you the problem. The JS is getElementById, but there's no ID is call figcaption.
var img = document.getElementById("figcaption");
The problem is that you are trying to use getElementById to find something with the id of figcaption; nothing on the page has an id of figcaption, so getElementById returns null.
There are a few ways you could fix it:
Add an id to your <figcaption> element: <figcaption id="figcaption">
Instead of using getElementById, use getElementsByTagName: document.getElementsByTagName('figcaption')[0];. (getElementsByTagName always returns a collection of elements, the [0] grabs the first, and in this case only, one in the collection).
Instead of using getElementById, use querySelector like you did to find the featured image element: document.querySelector("#featured figcaption");
This last approach of using querySelector is what I would recommend in this situation; other times it might be better to add an id to the element.
const thumbs = document.getElementById("thumbnails");
const featuredImage = document.querySelector("#featured img");
const caption = document.querySelector("#featured figcaption");
thumbs.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == 'img') {
var clickedImageSource = e.target.src;
// for the purposes of this demo, I'm using a placeholder
// image service so I need to change the size slightly differently
let newSrc = clickedImageSource.replace("50x50", "350x150");
//var newSrc = clickedImageSource.replace("small", "medium");
featuredImage.src = newSrc;
caption.textContent = e.target.title;
}
});
caption.addEventListener("mouseover",function (event) {
caption.className = "featured figcaption";
});
caption.addEventListener("mouseout", function (event) {
caption.className = "featured figcaption";
// I changed the value to .5 instead of .9 because with such small
// text the opacity change is barely perceivable.
caption.style.opacity = "0.5";
// This is not needed, this was the old way IE used to do it,
// IE < 9 needed it, but IE < 9 is no longer relevant. Just use opacity.
//element.style.filter = 'alpha(opacity=0%)';
});
<header>
<h2>Share Your Travels</h2>
<nav><img src="http://via.placeholder.com/50x50?text=Menu"></nav>
</header>
<main>
<figure id="featured">
<img src="http://via.placeholder.com/350x150" title="Battle">
<figcaption>Battle</figcaption>
</figure>
<div id="thumbnails">
<img src="http://via.placeholder.com/50x50" title="Battle">
<img src="http://via.placeholder.com/50x50/ff0000/ffffff" title="Luneburg">
<img src="http://via.placeholder.com/50x50/00ff00/ffffff" title="Bermuda">
<img src="http://via.placeholder.com/50x50/0000ff/ffffff" title="Athens">
<img src="http://via.placeholder.com/50x50/000000/ffffff" title="Florence">
</div>
</main>
A few things to note about my version, I used let and const instead of var. Both let and const are well supported these days and should be used instead of var unless you need to support very old browsers. I also only query for the caption and featured image elements once and store them in the scope above the click handler, this allows the code inside the click handler to have access to them via closure. This makes everything slightly more efficient since you don't have to query the DOM to find them each time the click handler runs. In this case the performance gain is moot but it is good to be in the habit of writing code as efficiently as possible so you don't have to think about it when it does matter.
Images are void elements, meaning they can't have any content, so you don't need a closing tag. For this reason I used bare <img> tags instead of self-closing <img /> tags. Self-closing images were only ever needed in XHTML, since it was XML, which has a more rigid syntax than HTML. Another thing to note, you don't need the type="text/javascript" on your <script> tags, it just takes up extra space and doesn't really do anything.
I don't understand what you are trying to do with the mouseover and mouseout handlers. Currently what your code does is:
When the mouse moves over the caption, the featured and figcaption classes are added to the caption.
When the mouse leaves the caption, the featured and figcaption classes are again added to the caption and its opacity is set to 0.9, effectively permanently.
I cleaned it up a little in my example to make it more obvious that is what is happening.

Enable Javascript function on image click

I had an image which appears on the click of another image.
I'm posting the code below. Please tell me where I went wrong. Thanks !
JavaScript
function suit1() {
var element = document.getElementById("suit1");
element.setAttribute("Hidden", "False");
}
HTML
<img src="suit1.png" style="width:100%; height:595px;" hidden="true" id="suit1"/>
<img src="point.png" onclick="javascript:suit1()">
Try this:
function suit1() {
var element = document.getElementById("suit1");
element.removeAttribute("hidden");
}
As stated in the comments, the number in suit1() was causing the issue. However, changing the function name to any name other than the id for first img resolves the problem. HTML:
<img src="suit1.png" style="width:100%; height:595px;" hidden="true" id="suit1"/>
<img src="point.png" onclick="javascript:some1()">
JavaScript:
function some1() {
var element = document.getElementById("suit1");
element.removeAttribute("hidden");
}
Or change the id of the img.

How to change an img src with javascript?

I know there are other questions like this and I've tried following them I'm just not aware of what exactly I'm doing wrong. I've declared the pic variable as being linked to the image with the corresponding id of 'pic' and I've tried many different examples and trying to follow other questions like this but to no avail.
--- THE REAL QUESTION ----
I would like the image to change its src to another one that I have in my workspace with the click of a button.
HTML:
<img class="trans" id="pic" src="images/link_rouge.png" alt="" width="1000" height="333" />
JavaScript:
var pic = document.getElementById('pic');
function rouge() {
pic.src = "images/link_rouge.png";
}
function blue() {
pic.src = "images/link_blue.png";
}
I know the functions already work with the buttons because they are affecting some divs on the page that change color the only things not changing are the images.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Use addEventListener over button elements to attach click events and bind your handler functions to those events.
var pic = document.getElementById('pic');
function rouge() {
pic.src = "http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png";
}
function blue() {
pic.src = "http://bin.smwcentral.net/u/1944/Link%2BBlue%2BTP%2Bshrunk.png";
}
document.getElementById('btn1').addEventListener('click', rouge);
document.getElementById('btn2').addEventListener('click', blue);
img {
width: 200px;
}
<button id='btn1'>rouge</button>
<button id='btn2'>blue</button>
<br/>
<img class="trans" id="pic" src="http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png" alt="" width="1000" height="333" />
There's a chance your page has not loaded before pic is set equal to document.getElementById('pic');.
You can use something like jQuery's $(document).ready() function (or document.addEventListener("DOMContentLoaded", handler);) to ensure your page is fully loaded before assigning the pic variable.
$( document ).ready(function() {
var pic = document.getElementById('pic');
function rouge() {
pic.src = "images/link_rouge.png";
}
function blue() {
pic.src = "images/link_blue.png";
}
});
Note: You will need to pull the JQuery library into your project to use this method. See here.
Also, you can read this post to learn a little more about HTML/JavaScript and page loading.

Using jQuery to detect if element has a certain style attribute

I'm writing a script to detect whether or not an image is present on a webpage. It's a standard formatting with their html for this section. If there is not an image it looks like
<div id="photo" style="display: none;">
<img id="image" src="IMAGESOURCE" onerror="img2txt()" alt="">
</div>
if there is an image present that same html looks like this
<div id="photo">
<img id="image" src="IMAGESOURCE" onerror="img2txt()" alt="">
</div>
Right now in the script I'm using this, which doesn't work (or i wouldn't be here :D )
var images = ($('#photo[style*="display: none"]').length === 0 ? false : true);
if (images) {
$('#yes[value="Yes"]').click();
}
else {
$('#no[value="No"]').click();
}
(The clicks are for the radio buttons on the form that I am filling out based on this image query)
As of right now the if/else statement is giving the radio "No" a click on a page where it should be a yes. I've tried using
if (!images) {
$('#yes[value="Yes"]').click();
}
else {
$('#no[value="No"]').click();
}
just to see if my boolean was incorrect. But with that adjustment it just does the opposite again. Any help is much appreciated. Thanks
So it is always display:none when not present? jQuery has a specific selector for that :visible.
var present = $("#photo").is(":visible");
To find out whether the image is visible or not:
$('#image:visible').length;
With reference to your own posted code, you could use:
var imageVisible = $('#image:visible').length,
toClick = imageVisible ? 'yes' : 'no';
$('#' + toClick + '[value=' + toClick + ']').click();
Or, avoiding the unnecessary attribute-selectors (given that an id is a unique identifier:
$('#' + toClick).click();
References:
:visible.

onmouseover function Javascript

I am having a problem with changing onmouseover and onmouseout attributes on dynamic pictures. The way i want it to work is whenever i put my mouse over images the images must change and when i take my mouse away it must be changed to the original picture. and whenever i select any image, that image must be changed to the image which was displayed while moving the mouse across the image. and when i select any other image the same process must take place but the previous image that was changed must be changed back to the original picture.
I have accomplished all of the above but my problem is when i select multiple pictures and put my mouse over images that were previously selected, those images do not change (onmouseover attribute does not work on them anymore).
<script language="javascript">
function changeleft(loca){
var od=''
var imgs = document.getElementById("leftsec").getElementsByTagName("img");
for (var i = 0, l = imgs.length; i < l; i++) {
od=imgs[i].id;
if(od==loca){
imgs[i].src="images/"+od+"_over.gif";
imgs[i].onmouseover="";
imgs[i].onmouseout="";
}else{
od = imgs[i].id;
imgs[i].src="images/"+od+".gif";
this.onmouseover = function (){this.src="images/"+od+"_over.gif";};
this.onmouseout = function (){this.src="images/"+od+".gif";};
}
}
}
</script>
<div class="leftsec" id="leftsec" >
<img id='wits' class="wits1" src="images/wits.gif" onmouseover="this.src='images/wits_over.gif'" onmouseout="this.src='images/wits.gif'" onclick="changeleft(this.id)" /><br />
<img id='city' class="city1" src="images/city.gif" onmouseover="this.src='images/city_over.gif'" onmouseout="this.src='images/city.gif'" onclick="changeleft(this.id)" /><br />
<img id='organise' class="city1" src="images/organise.gif" onmouseover="this.src='images/organise_over.gif'" onmouseout="this.src='images/organise.gif'" onclick="changeleft(this.id)" /><br />
<img id='people' class="city1" src="images/people.gif" onmouseover="this.src='images/people_over.gif'" onmouseout="this.src='images/people.gif'" onclick="changeleft(this.id)" /><br />
</div>
I'd say you don't need the lines that are resetting the onmouseover events.
There's no need to rewrite the onmouseover events - all you want to change is the img src attribute.
As Adam mentions, there's more modern ways to do this using jQuery - look at:
http://code.google.com/p/jquery-swapimage/
For example.

Categories