I am trying to change the image based when someone clicks on a link. I have coded this so far:
<script>
function changeImage(e) {
var elem, evt = e ? e:event;
alert("Event is"+evt.target);//for testing
var image = document.getElementById('myImage');
var feat1 = document.getElementById('feat1');
var feat2 = document.getElementById('feat2');
var feat3 = document.getElementById('feat3');
var feat4 = document.getElementById('feat4');
if (evt.target.match(feat1.href)) {
image.src = "";
} else {
image.src = "";
}
}
</script>
And HTML:
<li><a name="a" href="#1" onclick="changeImage()" id="feat1">a</a></li>
<li><a name="story" href="#2" onclick="changeImage()" id="feat2">b</a></li>
<li><a name="rep" href="#3" onclick="changeImage()" id="feat3">c</a></li>
<li><a name="reg" href="#3" onclick="changeImage()" id="feat4">d</a></li>
The image does not change. I am using the alert for testing. I am a bit new to javascript so how do I go about solving this?
Pass the reference of the current clicked link into onclick handler:
html part:
<li><a name="a" href="#1" onclick="changeImage(this)" id="feat1">a</a></li>
<li><a name="story" href="#2" onclick="changeImage(this)" id="feat2">b</a></li>
<li><a name="rep" href="#3" onclick="changeImage(this)" id="feat3">c</a></li>
<li><a name="reg" href="#3" onclick="changeImage(this)" id="feat4">d</a></li>
Optimize your js part as shown below:
<script>
function changeImage(e) {
var elem = e.currentTarget,
id = elem.id,
href = elem.href;
if (<your_condition>) { // exemplary code
image.src = "";
} else {
image.src = "";
}
}
</script>
First, you do know that in your example, the last two hyperlinks have the same name and href values, right?
Next, onclick as an inline event handler was never standard and is considered bad form. Instead use the DOM standard, addEventListener() as follows:
<body>
<li><a name="a" href="#1" id="feat1">a</a></li>
<li><a name="story" href="#2" id="feat2">b</a></li>
<li><a name="rep" href="#3" id="feat3">c</a></li>
<li><a name="reg" href="#4" id="feat4">d</a></li>
<img id="myImage" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/NASA_logo.svg/2000px-NASA_logo.svg.png" height="200">
<script>
(function(){
var theAnchors = document.querySelectorAll("a[id^='feat']");
for(var i = 0; i < theAnchors.length; ++i) {
theAnchors[i].addEventListener("click", function(){
changeImage(this);
});
}
function changeImage(targetAnchor) {
var image = document.getElementById('myImage');
var href = targetAnchor.href;
if (href.indexOf("#3") > -1) {
image.src = "http://www.nasa.gov/centers/jpl/images/content/650602main_pia15415-43.jpg";
} else {
alert("else");
image.src = "http://www.nasa.gov/centers/goddard/images/content/280046main_CassAcomposite_HI.jpg";
}
}
()); // IIFE
</script>
</body>
In the following JSFiddle, clicking a, b or d will result in the first image going away and a replacement coming up, but when you click c, a different image comes up. Be patient, by the way, these are hi-res images and take a few seconds to load.
Check out a working sample: https://jsfiddle.net/adspxoc5/5/
Related
I am learning about the DOM and incorporating Javascript in html files, I have tried this code that display and hide pictures using the event listener click. however, pictures don't seem to appear even no error is detected in the Chrome console.
NOTE: I only posted the concerned code, I omitted some of the HTML tags
<style>
.hide{
display: none;
}
</style>
<main>
<ul>
<li><a data-img="face" id="facebook" href="#"> Facebook </a></li>
<li><a data-img="insta" id="instagram" href="#"> Instagarm </a></li>
<li><a data-img="snap" id="snapchat" href="#"> Snapchat </a></li>
</ul>
<img class="hide" id="face" scr="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_square-128.png">
<img class="hide" id="insta" scr="http://bikecleanse.com/wp-content/uploads/2016/10/Insta-Logo.png" >
<img class="hide" id="snap" scr="https://icon-icons.com/icons2/686/PNG/512/snapchat_snap_chat_icon_logo_social_app_red_icon-icons.com_61225.png">
</main>
<script type="text/javascript">
var face = document.getElementById('facebook');
var insta = document.getElementById('instagram');
var snap = document.getElementById('snapchat');
face.addEventListener("click", show);
insta.addEventListener("click", show);
snap.addEventListener("click", show);
function show() {
var picId = this.attributes["data-img"].value;
var pic = document.getElementById(picId);
if(pic.className === "hide"){
pic.className="";
} else {
pic.className= "hide";
}
}
</script>
First off, you issues is that it is src and not scr, so change that attribute and the images will show.
Second, I would recommend using classList with add, remove and contains. You could also use toggle to make your code even smaller like so:
<style>
.hide {
display: none;
}
</style>
<main>
<ul>
<li> <a data-img="face" id="facebook" href="#"> Facebook </a> </li>
<li> <a data-img="insta" id="instagram" href="#"> Instagarm </a> </li>
<li> <a data-img="snap" id="snapchat" href="#"> Snapchat </a> </li>
</ul>
<img class="hide" id="face" src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_square-128.png">
<img class="hide" id="insta" src="http://bikecleanse.com/wp-content/uploads/2016/10/Insta-Logo.png">
<img class="hide" id="snap" src="https://icon-icons.com/icons2/686/PNG/512/snapchat_snap_chat_icon_logo_social_app_red_icon-icons.com_61225.png">
</main>
<script type="text/javascript">
var face = document.getElementById('facebook');
var insta = document.getElementById('instagram');
var snap = document.getElementById('snapchat');
face.addEventListener("click", show);
insta.addEventListener("click", show);
snap.addEventListener("click", show);
function show() {
var picId = this.attributes["data-img"].value;
var pic = document.getElementById(picId);
pic.classList.toggle('hide', !pic.classList.contains('hide'))
}
</script>
I added the event input to your show function. I modified your show function like below. Check if this works for you:
function show(e) {
let picId = e.target.dataset.img;
let pic = document.getElementById(picId);
if(pic.classList.contains('hide'){
pic.classList.remove('hide');
}
else{
pic.classList.add('hide');
}
}
I'm trying to write a callback function that fadein the next image after fadeout the old one. But it seems like I can fadeout the image but I only fadein the old image instead of the new one. I think the first $("#image") will be the old one, but I don't know why it's still the old image after I reset its attr. The same thing happens in the caption too.
This is my .js
$(document).ready(function() {
// set up event handlers for links
$("#image_list a").click(function(evt) {
$("#image").fadeOut(1000,
function(){
var imageURL = $(this).attr("href");
$("#image").attr("src", imageURL).fadeIn(1000);
});
$("#caption").fadeOut(1000,
function(){
var caption = $(this).attr("title");
$("#caption").text(caption).fadeIn(1000);
});
//var imageURL = $(this).attr("href");
//$("#image").attr("src", imageURL);
//$("#image").fadeIn(1000);
//var caption = $(this).attr("title");
//$("#caption").text(caption);
//$("#caption").fadeIn(1000);
// cancel the default action of the link
evt.preventDefault();
}); // end click
// move focus to first thumbnail
$("li:first-child a").focus();
}); // end ready
This is my .html
<body>
<main>
<h1>Ram Tap Combined Test</h1>
<ul id="image_list">
<li><a href="images/h1.jpg" title="James Allison: 1-1">
<img src="thumbnails/t1.jpg" alt=""></a></li>
<li><a href="images/h2.jpg" title="James Allison: 1-2">
<img src="thumbnails/t2.jpg" alt=""></a></li>
<li><a href="images/h3.jpg" title="James Allison: 1-3">
<img src="thumbnails/t3.jpg" alt=""></a></li>
<li><a href="images/h4.jpg" title="James Allison: 1-4">
<img src="thumbnails/t4.jpg" alt=""></a></li>
<li><a href="images/h5.jpg" title="James Allison: 1-5">
<img src="thumbnails/t5.jpg" alt=""></a></li>
<li><a href="images/h6.jpg" title="James Allison: 1-6">
<img src="thumbnails/t6.jpg" alt=""></a></li>
</ul>
<h2 id="caption">James Allison: 1-1</h2>
<p><img src="images/h1.jpg" alt="" id="image"></p>
</main>
</body>
</html>
It's a problem with this, note that as replacement of this
$("#image_list a").click(function(evt) {
// Here this is element of #image_list a
var that = this;
$("#image").fadeOut(1000, function(){
// Here this is element of #image
var imageURL = $(that).attr("href");
$("#image").attr("src", imageURL).fadeIn(1000);
});
$("#caption").fadeOut(1000, function(){
// Here this is element of #image
var caption = $(that).attr("title");
$("#caption").text(caption).fadeIn(1000);
});
//var imageURL = $(this).attr("href");
//$("#image").attr("src", imageURL);
//$("#image").fadeIn(1000);
//var caption = $(this).attr("title");
//$("#caption").text(caption);
//$("#caption").fadeIn(1000);
// cancel the default action of the link
evt.preventDefault();
}); // end click
I would like a javascript method to display image in div depending on which a href link is clicked.
I have written some code but it needs developing further.
<script type=" ">
function changeImg(){
var image1 = new Image();
image1.src='car.png'
var imghol = document.getElementById("imageHolder");
var elements = document.getElementById("FS");
if(elements.onclick = function()){
imghol = image1;
}
</script>
<div class="ADS2"><h2>Vehicle Part</h2><p>Please select a part you wish to find;
<div class="vertical_menu">
<ul>
<li><a id="FS" href="#home" onclick="changeImg">Front Side</a></li>
<li><a id="RS" href="#news">Rear Side</a></li>
<li><a id="S" href="#contact">Side</a></li>
<li><a id="US"href="#about">Under Side</a></li>
<li><a id="I" href="#about">Interior</a></li>
</ul>
</div>
<div class="imageholder">
</div>
</div>
Keep it simple. Try this:
<script type="text/javascript">
function changeImg(image){
var imghol = document.getElementById("imageHolder");
imghol.src = image;
}
</script>
<div class="ADS2">
<h2>Vehicle Part</h2>
<p>Please select a part you wish to find;</p>
<div class="vertical_menu">
<ul>
<li><a id="FS" href="javascript:" onclick="changeImg('car.jpg');">Front Side</a></li>
<li><a id="RS" href="javascript:" onclick="changeImg('rear.png')">Rear Side</a></li>
<li><a id="S" href="javascript:" onclick="changeImg('caside.png')">Side</a></li>
<li><a id="US" href="javascript:" onclick="changeImg('under.png')">Under Side</a></li>
<li><a id="I" href="javascript:" onclick="changeImg('interior.png')">Interior</a></li>
</ul>
</div>
<div class="imageholder"><img id="imageHolder" /></div>
</div>
use this
HTML
<a onclick="changeImg('pic1.png')">Link 1</a>
<a onclick="changeImg('pic2.png')">Link 2</a>
<a onclick="changeImg('pic3.png')">Link 3</a>
<a onclick="changeImg('pic4.png')">Link 4</a>
.....
<div class="imageholder">
<img id="change_img_target" />
</div>
Javascript
function changeImg(url) {
document.getElementById("change_img_target").src = url;
}
You can also achieve this with jQuery. Be sure to include the jQuery library in your file. :)
HTML:
Link 1
Link 2
<div id="div">
</div>
jQuery (add this to the bottom of your page):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
function changeImg(url) {
var image = "<img src='url' />";
$("#div").html(image);
}
});
</script>
# Naveen,
You can achieve the solution using any of the following 2 answers.
Ans1:
<script type="text/javascript">
function preloader()
{
var imgs = ['chart1.jpg','chart2.jpg','chart3.jpg','chart4.jpg','chart5.jpg']; // take array of images
var container = document.getElementById('photos');
var docFrag = document.createDocumentFragment();
imgs.forEach(function(url, index, originalArray) {
var img = document.createElement('img');
img.src = url;
docFragenter code here.appendChild(img);
});
container.appendChild(docFrag);
}
</script>
<body onload="preloader();">
<div>
<table width="100%" style="height: 100%;" border="0">
<tr>
<td>
<p id="photos" onclick="preloader()" />
</td>
</tr>
</table>`
</div>
Ans2:
function preloader()
{
var imgs=['chart1.jpg','chart2.jpg','chart3.jpg','chart4.jpg','chart5.jpg'];
var container = document.getElementById('photos');
for (var i = 0, j = imgs.length; i < j; i++) {
var img = document.createElement('img');
img.src = imgs[i]; // img[i] refers to the current URL.
container.appendChild(img);
}
}
Link for more Help:
How to add a list of images to the document from an array of URLs?
I have the following jQuery code:
<script>
var init = function() {
// Resize the canvases)
for (i = 1; i <= 9; i++) {
var s = "snowfall" + i
var canvas = document.getElementById(s);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Now the emitter
var emitter = Object.create(rectangleEmitter);
emitter.setCanvas(canvas);
emitter.setBlastZone(0, -10, canvas.width, 1);
emitter.particle = snow;
emitter.runAhead(60);
emitter.start(30);
}
$("canvas").delay(10000).animate({
opacity: '0',
});
};
</script>
<ul class="nav navbar-nav">
<li class="fst"><span class="icon-menu" /> Home
</li>
<li class="fst"><span class="icon-menu" /> About us
</li>
<li class="fst"><span class="icon-menu" /> Products
</li>
<li class="fst"><span class="icon-menu" /> Franchising
</li>
<li class="fst"><span class="icon-menu" /> News
</li>
</ul>
I want to use this jQuery code to all href tabs.
I tried to use the click function, in that case only the first tab works well, the rest don't work at all.
Can any one explain me?
$('.navbar-nav a').click(function(e) {
e.preventDefault();
var data = $(this).data('href');
// do whatever you need
});
Based off of #Petar Vasilev's answer
http://jsfiddle.net/dHR8V/2/
$('.navbar-nav a').click(function(e) {
e.preventDefault();
debugger;
window.location.href = "someurl";
// do whatever you need
});
When you click a link the handler captures the click event and is executed. You now have control of whatever happens when a link is clicked.
Here is the function I'm using:
jOWL.load("owldoc.owl", function(){});
jOWL.load takes in an owl document as a parameter (as seen above). I have 3 of these documents on the server, and would like the user to be able to chose which document to load by pressing a button.
I wonder if it is possible to have a string 'owldoc.owl', 'owldoc2.owl', or 'owldoc3.owl' passed to a javascript variable, which could then be passed in as a parameter to jOWL.load
How would I go about this?
Call the function below using onclick='loadFile("1"); return false;' inside of the respective link.
i.e.:
<a href="" id='load1'>Load 1</a>
<a href="" id='load2'>Load 2</a>
<a href="" id='load3'>Load 3</a>
function:
function loadFile(param){
jOWL.load("owldoc"+param+".owl", function(){});
}
To have onclicks that do not show up in line, the easiest way is to add ids to the anchors and call this function on page load using manageOnclicks();:
function manageOnclicks(){
document.getElementById('load1').onclick = function(){loadFile('1'); return false;}
document.getElementById('load2').onclick = function(){loadFile('2'); return false;}
document.getElementById('load3').onclick = function(){loadFile('3'); return false;}
}
Sample HTML
<input type='button' onclick="loadFile('owldoc.owl')" value='Load Owldoc'/>
<input type='button' onclick="loadFile('owldoc2.owl')" value='Load Owldoc2'/>
<input type='button' onclick="loadFile('owldoc3.owl')" value='Load Owldoc3'/>
Javascript
function loadFile(fileName) {
// filename contains the variable
// you can now do
//jOWL.load(filename, function(){}
}
Something like:
HTML:
<h3>Choose a file to load</h3>
<ul id='choose_file'>
<li><a data-file='1'>File 1</a></li>
<li><a data-file='2'>File 2</a></li>
<li><a data-file='3'>File 3</a></li>
</ul>
JS
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#choose_file').addEventListener('click', function(evt) {
var file_to_load = evt.target.getAttribute('data-file');
jOWL.load('owldoc'+file_to_load+'.owl', function() {
/* callback code here */
});
}, false);
}, false);