So i am trying to make it so if you click on the button it will switch the images placement. However it doesnt actually switch the placement but instead just changes the src of each image ID. It works when you click the button once, but after that the images no longer switch. This is my code
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src = '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src = '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The problem is the src property will have the absolute path to the image, not relative one as you are checking
One possible solution is to use .indexOf() as given below
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src.indexOf('/jmurphy9/111/images/earthrise.jpg')>-1) {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src.indexOf( '/jmurphy9/111/images/earth.jpg')>-1) {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
Or you can use .getAttribute()
if (image1.getAttribute('src') == '/jmurphy9/111/images/earthrise.jpg') {
}
But since you want to swap, you can just do
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
var src = image1.src;
image1.src = image2.src;
image2.src = src;
}
Demo: Fiddle
Note: In your if condition you are using assignment(=) operator instead of comparison operator(==), so image1.src = '/jmurphy9/111/images/earthrise.jpg' in the if should be image1.src == '/jmurphy9/111/images/earthrise.jpg'
Looks like your equality operator is missing an extra "=" on your if's e.g. if(image1.src == '/jmurphy9/111/images/earthrise.jpg') so when it tries to evaluate the expression it never goes in so it changes the first time 'cause it goes to the else and from there on it just keeps going to the else so nothing happens.
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src == '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src == '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The accepted answer, like yours, swaps the src attribute of the images.
Another method is to actually swap the img nodes themselves, which may be preferable if the images matter severally- eg., need special event handling or css considerations that depend on the actual image.
function swapNodes(a, b){
var p= b.parentNode, sib= b.nextSibling;
if(sib=== a) sib= sib.nextSibling;
a.parentNode.replaceChild(b, a);
return sib? p.insertBefore(a, sib): p.appendChild(a);
}
note that you can always swap img nodes, or any two like nodes, but there are some nodes that cannot be swapped, because the container node of one will not accept the other as a child.
You can swap them if they make valid html.
Related
I have the following code to create an image with JavaScipt, the image appear on a button click. The problem is when the image is created and i click again the button another one appear, and i don't want that.
How i can solve that?
var img = new Image();
var div = document.getElementById('Table');
img.onload = function() {
div.appendChild(img);
};
img.src = 'Images/Email.png';
You could use a flag, which indicate when the image has been created, loaded and added to your DOM:
var div = document.getElementById('Table');
var hasImage = false; // flag
var button = document.getElementById('button');
button.addEventListener('click', function(event){
createImage();
});
var createImage = function(){
if(!hasImage) {
var img = new Image();
img.src = 'http://pipsum.com/435x310.jpg';
img.onload = function() {
div.appendChild(img);
hasImage = true;
};
}else{
console.log('image is already present');
}
};
<button id="button" type="button">Click Me!</button>
<div id="Table"></div >
Check if the image is already added to the DOM. If not, do so. If already added, only update the source.
It could be something like this:
var img = new Image();
var div = document.getElementById('Table');
var appended = false;
function appendImage() {
appended = true;
div.appendChild(img);
img.removeEventListener('load', appendImage);
}
function onClick() {
if (!appended) {
img.addEventListener('load', appendImage);
}
img.src = 'Images/Email.png';
}
I'm currently learning JavaScript at my university, so I apologize if my code is terrible. I'm new to it.
I'm having an issue only changing one image onclick using appendChild. What I want to happen is that if the person clicks on the image whose rng is <= 0.89, then only that image is changed to a different image. Every thing I've tried has changed all of the images whose rng was <=0.89.
Example: I click the first image (img1) which has rolled a number greater than 0.9. If (img2) has rolled the same (greater than 0.9), then it also changes. I'd only want img1 to change. Here is only some of my code as the whole thing is about 150 lines and I think this bit gets my point across somewhat well:
function myFunction() {
var rng=Math.random();
var rng2=Math.random();
if (rng <= 0.89){
var img1=document.createElement('img');
img1.src='card2.gif';
img1.id="bad1";
img1.onclick = goodbye;
document.getElementById('card').appendChild(img1);
}
if (rng2 <= 0.89){
var img2=document.createElement('img');
img2.src='card2.gif';
img2.onclick= goodbye;
img2.id="bad2";
document.getElementById('card2').appendChild(img2);
}
if (rng >= 0.9) {
var img1=document.createElement('img');
img1.src='card3.gif';
img1.id="good1";
img1.onclick = hello;
document.getElementById('card').appendChild(img1);
}
if (rng2 >= 0.9){
var img2=document.createElement('img');
img2.src='card3.gif';
img2.onclick= hello;
img2.id="good2";
document.getElementById('card2').appendChild(img2);
}
}
Like I said, every thing I've tried to only change the image that was clicked has changed all images whose rng is <=0.89. The answer's probably really obvious, but I'm new to this, like I said.
Based on the comments, the only change that your code needs is to make .onclick set to a function instead of a string. This way we also pass this the element reference to your functions goodbye and hello. You can also use this to read the element properties if you wanted to. If this is not what your looking for let us know.
img1.onclick = function(){goodbye(this)};
Script
function goodbye(e) {
e.src = 'https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png'
}
function hello(e) {
e.src = 'https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I.jpg'
}
function myFunction() {
var rng = Math.random();
var rng2 = Math.random();
if (rng <= 0.89) {
var img1 = document.createElement('img');
img1.src = 'card2.gif';
img1.id = "bad1";
img1.onclick = function () {
goodbye(this)
};
document.getElementById('card').appendChild(img1);
}
if (rng2 <= 0.89) {
var img2 = document.createElement('img');
img2.src = 'card2.gif';
img2.onclick = function () {
goodbye(this)
};
img2.id = "bad2";
document.getElementById('card2').appendChild(img2);
}
if (rng >= 0.9) {
var img1 = document.createElement('img');
img1.src = 'card3.gif';
img1.id = "good1";
img1.onclick = function () {
hello(this)
};
document.getElementById('card').appendChild(img1);
}
if (rng2 >= 0.9) {
var img2 = document.createElement('img');
img2.src = 'card3.gif';
img2.onclick = function () {
hello(this)
};
img2.id = "good2";
document.getElementById('card2').appendChild(img2);
}
}
jsfiddle if required
I am currently working on SVG SMIL animation in which I am using some .png and .gif files for easing my animation in IE. For this animation I am trying to get Preloader before animation and its other contents get loaded.
Problem is I am not getting that Preloader working properly. My .html page is getting loaded first and then preloader is starting... In Preloader also, I have used several preloaders available on the web. But they are not helpful for me.
Script and .html files loading time can be counted by domContentLoaded but for images. I dont know how to do that. If someone can suggest me a way that would be great.
here is code of preloader.js, I found on web:
$(document).ready(function () {
"use strict"
//indexOf support for IE8 and below.
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
//bgImg for holding background images in the page & img array for images present in the document(<img src="">).
var bgImg = [], img = [], count=0, percentage = 0;
//Creating loader holder.
$('<div id="loaderMask"><span>0%</span></div>').css({
position:"fixed",
top:0,
bottom:0,
left:0,
right:0,
background:'#fff'
}).appendTo('body');
//Using jQuery filter method we parse all elemnts in the page and adds background image url & images src into respective arrays.
$('*').filter(function() {
var val = $(this).css('background-image').replace(/url\(/g,'').replace(/\)/,'').replace(/"/g,'');
var imgVal = $(this).not('image').attr('xlink:href');
//Getting urls of background images.
if(val !== 'none' && !/linear-gradient/g.test(val) && bgImg.indexOf(val) === -1){
bgImg.push(val)
}
//Getting src of images in the document.
if(imgVal !== undefined && img.indexOf(imgVal) === -1){
img.push(imgVal)
}
});
//Merging both bg image array & img src array
var imgArray = bgImg.concat(img);
console.log(imgArray.length);
//Adding events for all the images in the array.
$.each(imgArray, function(i,val){
//Attaching load event
$("<image />").attr("xlink:href", val).bind("load", function () {
console.log('val'+val);
completeImageLoading();
});
//Attaching error event
$("<image />").attr("xlink:href", val).bind("error", function () {
imgError(this);
});
})
//After each successful image load we will create percentage.
function completeImageLoading(){
count++;
percentage = Math.floor(count / imgArray.length * 100);
console.log('percentage:'+percentage);
$('#loaderMask').html('<span>'+percentage + '%'+'</span>');
//When percentage is 100 we will remove loader and display page.
if(percentage == 100){
$('#loaderMask').html('<span>100%</span>')
$('#loaderMask').fadeOut(function(){
$('#loaderMask').remove()
})
}
}
//Error handling - When image fails to load we will remove the mask & shows the page.
function imgError (arg) {
$('#loaderMask').html("Image failed to load.. Loader quitting..").delay(3000).fadeOut(1000, function(){
$('#loaderMask').remove();
})
}
});
A little trick I do to ensure my or external data or images are loaded before I start executing my js code is, I create a div with display:none and fill it with all the tags that I need loaded.
<body>
<span id="loadingText">Loading...</span>
<div style="display:none">
<img src="pathtoimage1">
<img src="pathtoimage2">
<img src="pathtoimage3">
</div>
<script>
window.onload = function(){
//This gets called when all the items in that div has been loaded and cached.
document.getElementById("loadingText").style.display = "none";
}
</script>
</body>
I use this for preloading images for animations.
you can add and remove how many you load as needed.
<script language="javascript">function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var img5 = new Image();
var img6 = new Image();
var img7 = new Image();
var img8 = new Image();
var img9 = new Image();
img1.src = "image link here";
img2.src = "image link here";
img3.src = "image link here";
img4.src = "image link here";
img5.src = "image link here";
img6.src = "image link here";
img7.src = "image link here";
img8.src = "image link here";
img9.src = "image link here";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);</script>
I've only started HTML yesterday and I'm trying to do a really basic memory game. First, there's an image of all the pieces, then a button that calls a function that hides that image and make another appear. This second image is a blank page with the spaces where the parts of the former image were. Also, there's an usemap and a function that returns if the player has clicked correctly or not. My problem is to come up with a function (and how to call it) to select a random part of the image.
function checkAnswer(a) {
if (a=='6') {
alert('Correct!')
}
else {
alert('Wrong!')
}
}
The 'a' must be a random number and follow the index of the chosen picture.
This is what I've found, but couldn't use:
<!-- Attempt of random
function random_imglink() {
var cobras=new Array()
cobras[1]="<img src ="..\images\Cobra1.jpg">"
cobras[2]="..\images\Cobra2.jpg"
cobras[3]="..\images\cobra3.jpg"
cobras[4]="..\images\cobra4.jpg"
cobras[5]="..\images\cobra5.jpg"
cobras[6]="..\images\cobra6.jpg"
cobras[7]="..\images\cobra7.jpg"
cobras[8]="..\images\cobra8.jpg"
cobras[9]="..\images\cobra9.jpg"
cobras[10]="..\images\cobra10.jpg"
cobras[11]="..\images\cobra11.jpg"
cobras[12]="..\images\cobra12.jpg"
cobras[13]="..\images\cobra13.jpg"
cobras[14]="..\images\cobra14.jpg"
cobras[15]="..\images\cobra15.jpg"
var ry=Math.floor(Math.random()*cobras.length)
if (ry=='0') {
ry = '1'
}
document.write('<img src="'+myimages[ry]+'" border=0>')
}
-->
<!-- Attempt of random
<script>
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '..\images\Cobra1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '..\images\Cobra2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '..\images\cobra3.jpg';
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
</script>
I'm building a navigation bar where the images should be swapped out on mouseover; normally I use CSS for this but this time I'm trying to figure out javascript. This is what I have right now:
HTML:
<li class="bio"><img src="images/nav/bio.jpg" name="bio" /></li>
Javascript:
if (document.images) {
var bio_up = new Image();
bio_up.src = "images/nav/bio.jpg";
var bio_over = new Image();
bio_over.src = "images/nav/bio-ov.jpg";
}
function over_bio() {
if (document.images) {
document["bio"].src = bio_over.src
}
}
function up_bio() {
if (document.images) {
document["bio"].src = bio_up.src
}
}
However, all of the images have names of the form "xyz.jpg" and "xyz-ov.jpg", so I would prefer to just have a generic function that works for every image in the navbar, rather than a separate function for each image.
A quick-fire solution which should be robust enough provided all your images are of the same type:
$("li.bio a").hover(function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace(".jpg", "") + "-ov.jpg";
}, function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace("-ov.jpg", "") + ".jpg";
});
This should work will all image formats as long as the extension is between 2 and 4 characters long IE. png, jpeg, jpg, gif etc.
var images = document.getElementById('navbar').getElementsByTagName('img'), i;
for(i = 0; i < images.length; i++){
images[i].onmouseover = function(){
this.src = this.src.replace(/^(.*)(\.\w{2,4})$/, '$1'+'-ov'+'$2');
}
images[i].onmouseout = function(){
this.src = this.src.replace(/^(.*)-ov(\.\w{2,4})$/, '$1'+'$2');
}
}
Here's an idea in plain javascript (no jQuery):
function onMouseOverSwap(e) {
e.src = e.src.replace(/\.jpg$/", "-ov.jpg"); // add -ov onto end
}
function onMouseOutSwap(e) {
e.src = e.src.replace(/(-ov)+\.jpg$/, ".jpg"); // remove -ov
}