toggle image via onclick issue javascript - javascript

I am trying to toggle between two images I have in a folder via an onclick function. Currently my code does not toggle the image and I am getting no console errors, so I don't know why the toggle is not occurring. my folders look like this:
program-01
program01.index
program01javascript
program01script.js
program01css
images
LightOff.png
LightOn.png
HTML
<div>
<img src="images/LightOff.png" id="light" onclick="DateTime(); imageSwap();" />
<p id="date_time"></p>
</div>
Javascript
function imageSwap(){
var img = document.getElementById("light") ;
if (img.src == "images/LightOff.png"){
img.src = "images/LightOn.png";
} else {
img.src = "images/LightOff.png";
}
}
I believe it has have something to do with my file path and or something to do with the .src property, but unsure of exactly what the issue is.

How about this ?
img.src will return absolute url, I would suggest you to play with the flags instead of image src
var status = false;
function imageSwap() {
var img = document.getElementById("light");
if (!status) {
img.src = "images/LightOn.png";
status = true;
} else {
img.src = "images/LightOff.png";
status = false;
}
}
Or doing it your way, use getAttribute
function imageSwap(){
var img = document.getElementById("light") ;
if (img.getAttribute('src') == "images/LightOff.png"){
img.src = "images/LightOn.png";
} else {
img.src = "images/LightOff.png";
}
}

Related

i want to flip between two images by clicking on the image itself using javascript

i want to flip between two images by clicking on the image itself. help me with the code(i want the most simplified answer, very new learner)
function changeImage(){
var img = document.createElement('img')
img.src =="images/pic2.jpg"
let displayImage = document.getElementById('first')
if (displayImage.getAttribute("src") =="images/pic.jpg") {
document.getElementById('first').appendChild(img);
}
}
You can just change the src attribute of the image.
function switchImage () {
let element = document.getElementById("myImg")
if (element.src == "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg") {
element.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Aquilegia_vulgaris_100503c.jpg/420px-Aquilegia_vulgaris_100503c.jpg"
} else {
element.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg"
}
}
<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg" onclick="switchImage()" />

How can i call onerror() callback for an <object> SVG tag in Chome only

In chrome and Firefox the below issue doesn't work. it works in IE.
I have an element object which i create dynamically using JS:
svg = document.createElement("object");
svg.setAttribute("type","image/svg+xml");
svg.setAttribute("data",url);
mycanvas.appendChild(svg);
this successfully creates an object element with an svg inside it when i load a file that actually exists:
but when the file doesn't exist i get:
in which case i want to call an onerror() callback which i have created.
at the moment it looks like:
svg.onerror = function() {
alert("not found");
};
but this onerror() doesn't get called because it looks for svg and svg is the object tag which is created regardless of the svg (image 2 above).
how can i check to see if the image is empty or non-existant (image 2 above) then call onerror.
i believe i need to something like:
var callback = document.getElementsByTagName("object")[0].contentDocument;
callback.onerror = function() {
alert("not found");
};
the above fails but it was just a quick attempt i made.
any ideas?
thanks in advance.
I used this helper function that enables us to detect also 404 error (wrong svg url): Detecting an image 404 in javascript
Look at the demo: it loads the Chrome logo as an SVG and draws it on the 1st canvas, and the same code with an wrong url alerts "error2"
// First a couple helper functions
function $(id) {
return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) { return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;}
// Here's the meat and potatoes
function image(src,cfg) { var img, prop, target;
cfg = cfg || (isType(src,'o') ? src : {});
img = $(src);
if (img) {
src = cfg.src || img.src;
} else {
img = document.createElement('img');
src = src || cfg.src;
}
if (!src) {
return null;
}
prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
img.alt = cfg.alt || img.alt;
// Add the image and insert if requested (must be on DOM to load or
// pull from cache)
img.src = src;
target = $(cfg.target);
if (target) {
target.insertBefore(img, $(cfg.insertBefore) || null);
}
// Loaded?
if (img.complete) {
if (img[prop]) {
if (isType(cfg.success,'f')) {
cfg.success.call(img);
}
} else {
if (isType(cfg.failure,'f')) {
cfg.failure.call(img);
}
}
} else {
if (isType(cfg.success,'f')) {
img.onload = cfg.success;
}
if (isType(cfg.failure,'f')) {
img.onerror = cfg.failure;
}
}
return img;
}
// and here's how it's used:
url = "https://images3.wikia.nocookie.net/__cb20120330024139/logopedia/images/d/d7/Google_Chrome_logo_2011.svg";
// first one that shows the image:
var mycanvas = document.getElementById("c");
var ctx = mycanvas.getContext('2d');
var img = image(url, {
success:function(){ctx.drawImage(img, 0, 0);},
failure:function(){alert("error1");}
});
// second one that has 404 error:
var mycanvas2 = document.getElementById("d");
var ctx2 = mycanvas2.getContext('2d');
var img2 = image("http://example.com/a.svg", {
success:function(imga){ctx2.drawImage(img2, 0, 0);},
failure:function(){alert("error2");}
});
canvas{border: 1px solid #f00}
c:<canvas id="c" width="250" height="250"></canvas>
d:<canvas id="d" width="250" height="250"></canvas>
Note, that technically this works not with an object, but an img, if I understood what is your intention then that shouldn't matter, because the goal is to draw it onto the canvas, and this code does exactly that.

Changing Images src with Event "onclick"

<!DOCTYPE html>
<html>
<body>
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor()"/>
<script>
var image = document.getElementById("imageOne");
function changeColor() {
if (image.src == "circleRed.png") {
image.src = "circleBlue.png";
} else {
image.src = "circleRed.png";
}
}
</script>
</body>
</html>
This whole program may seem to work but no. I'll just be able to change the color of my image once. After clicking for the second time, nothing happens. What I mean is that I can only change the color from Red to Blue.
Could you please help me figure out why?
Here is the solution:
<!DOCTYPE html>
<html>
<body>
<img id ="imageOne" src ="circleRed.png" onclick = "changeColor()"/>
<script>
var image = document.getElementById("imageOne");
function changeColor()
{
if (image.getAttribute('src') == "circleRed.png")
{
image.src = "circleBlue.png";
}
else
{
image.src = "circleRed.png";
}
}
</script>
</body>
</html>
var image = document.getElementById("imageOne");
Move this inside function before if statement
image.src returns the physical path of image. So you can use indexOf to match image name. Following code snippet may help you.
function changeColor(image) {
if (image.src.indexOf("circleRed.png")>-1) {
image.src = "circleBlue.png";
} else {
image.src = "circleRed.png";
}
}
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>
try this code. just make sure to use (img.src.match)
.And script inside the body.
var img = document.getElementById("image1");
img.addEventListener("mouseover", function(){
if(img.src.match("images/image1.jpg")){
img.src ="images/image1_2.jpg";}
else {
img.src = "images/image1.jpg"
}
})
<img src="images/image1.jpg" id="image1" />
function changeColor(image) {
if (image.src.indexOf("circleRed.png")>-1) {
image.src = "circleBlue.png";
} else {
image.src = "circleRed.png";
}
}
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>

How to toggle images

I am a programming fool,
All I need is to be able to toggle two images, one which acts as the 'up state' of a button and then 'onclick' the second image appears and remains until it is clicked again whereby it is replaced by the the 'upstate image'.
Please don't mock me for this pitifull attempt which fails miserably. Here is my code.
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change()"/>
Thank you in anticipation.
Check this demo.
function change(image) {
if (image.src.indexOf("imgd1.svg") > -1){
image.src ="imgd1over.svg";
}
else{
image.src ="imgd1.svg";
}
}
In the fiddle case the image.src wasn't just the image's name, but the full url: http://fiddle.jshell.net/_display/imgd1.svg. So I have used indexOf() to check if the image's source constains the string you want.
Besides, I have changed the way change() function references to the image:
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change(this)"/>
Using change(this) will set the own image as the first parameter of the event, so you don't need to get it in the window object or event with getElementById or whatever.
function change() {
var image = document.getElementById("test");
if (image.src.indexOf("imgd1.svg") > -1 ){
image.src = "imgd1over.svg";
}
else if(image.src.indexOf("imgd1over.svg") > -1 ){
image.src = "imgd1.svg";
}
}
Here is the working code:
<img src ="imgd1.svg" name="pic" onclick="change();"/>
<script>
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
}
<script>
See the full demo:
http://jsfiddle.net/jswsze5q/
Try this:
<script>
function change() {
var img1 = "imgd1.svg",
img2 = "imgd1over.svg";
var imgElement = document.getElementById('test');
imgElement.src = (imgElement.src === img1)? img2 : img1;
}
</script>
<img src="imgd1.svg" id="test" onclick="change();"/>
Example: jsfiddle
Try using Jquery
var flag = 0;
function change(){
if(flag){
$("#img").attr("src","img1.png");
flag = 0;
}
else{
$("#img").attr("src","img2.png");
flag = 1;
}
}
Simplest toggle option
where variable flag acts as flag which detects which image is active
img is the id of image control.
Code to include Jquery from google CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

How can I check if the href path contain image or someother link using javascript or jquery?

Any One Know Tell me the suggestion to do this. How can i check if the anchor href attribute contain image path or some other path.
For Example:
<img src="image.jpg"/>
<img src="image.jpg"/>
See the above example shows href attribute contain different path like first one is the image and second one is the some other site link. I still confuse with that how can i check if the href path contain the image path or some other path using jquery or javascript.
Any suggestion would be great.
For example (you may need to include other pic formats if needed):
$("a").each(function(i, el) {
var href_value = el.href;
if (/\.(jpg|png|gif)$/.test(href_value)) {
console.log(href_value + " is a pic");
} else {
console.log(href_value + " is not a pic");
}
});
Jquery:
$(document).ready( function() {
var checkhref = $('a').attr('href');
var image_check = checkhref.substr(checkhref.length - 4)
http_tag = "http";
image = [".png",".jpg",".bmp"]
if(checkhref.search("http_tag") >= 0){
alert('Http!');
//Do something
}
if($.inArray(image_check, image) > -1){
alert('Image!');
//Do something
}
});
you may check if image exists or not, without jQuery
Fiddle
var imagesrc = 'http://domain.com/image.jpg';
function checkImage(src) {
var img = new Image();
img.onload = function() {
document.getElementById("iddiv").innerHTML = src +" exists";
};
img.onerror = function() {
document.getElementById("iddiv").innerHTML = src +"does not exists";
};
img.src = src; // fires off loading of image
return src;
}
checkImage(imagesrc);

Categories