JQuery: toggle conditions - javascript

I'm trying to add a toggle button to my website wherein it enables or disables the functionality of a certain feature, however while testing it, I bump into a problem wherein it does not alert even if the toggle works or the image changed. How can I make it work, any help and suggestion is appreciated.
HTML:
<img id="toggle-video" src="/images/Icons/10_device_access_video.png"
style="background-color:#C0C0C0; height: 20px; width:20px;" alt="" />
<img id="toggle-volume" src="/images/Icons/10_device_access_volume_on.png"
style="background-color:#C0C0C0; height: 20px; width:20px; margin-left:-5px;" alt="" />
JQUERY:
$("#toggle-video").on({'click':function() {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == '/images/Icons/10_device_access_video.png') src = '/images/Icons/10_device_stop_video.png';
// {
// alert(video success);
// }
if (origsrc == '/images/Icons/10_device_stop_video.png') src = '/images/Icons/10_device_access_video.png';
// {
// alert(volume success);
// }
$(this).attr('src', src);
}
});

You need to place the code which change the src value inside { } of your if condition:
$("#toggle-video").on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == '/images/Icons/10_device_access_video.png') {
src = '/images/Icons/10_device_stop_video.png';
alert('video success');
}
if (origsrc == '/images/Icons/10_device_stop_video.png') {
src = '/images/Icons/10_device_access_video.png';
alert('volume success');
}
$(this).attr('src', src);
}
});
Fiddle Demo

Code works fine.
You are trying to alert variables instead of string
alert(video success);
alert(volume success);
alert(`video success`);
alert(`volume success`);

Related

How to check image url is 404 using javascript

Use Case:
when src is not null and alt tag is not null then show image of src.
then check src image url is not 404.
when src is null and alt is not null the show image of first name.
when src and alt are null then show default image
HTML:
<img class="imagelazy" id="lazyimage" src="http://url" alt="ankit">
Javascript:
function imagelazy() {
$(document).ready(function()
{
var image = $(".imagelazy").attr('src');
var altdata = $(".imagelazy").attr('alt');
var alt = $(".imagelazy").attr('alt').split("");
//var imagepath="http://im.gifbt.com/userimages/"+alt[0].toLowerCase()+".jpg";
var defaultimage = "http://im.gifbt.com/img/no-pic.jpg";
console.log(image);
console.log(alt);
$(".imagelazy img")
.error(function() {
$(this).hide();
})
.attr("src", defaultimage);
if (image != '' && altdata != '') {
console.log("afeef");
$('.imagelazy').bind('error', function() {
$(this).attr("src", defaultimage);
});
$(".imagelazy img")
.error(function() {
$(this).hide();
})
.attr("src", defaultimage);
} else if (image == '' && altdata != '') {
$.each($('.imagelazy'), function(index, value) {
var alt1 = $(this).attr('alt').split("");
console.log(alt1);
if (alt1 != '') {
var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
}
console.log(this.outerHTML);
console.log(imagepath1);
$(this).attr("src", imagepath1);
});
} else if (altdata == '' && image == '') {
$.each($('.imagelazy'), function(index, value) {
$(this).attr("src", defaultimage);
console.log(this.outerHTML);
});
}
});
}
Problem
Script is not working when scrolling down the page.
When the image is set in src and alt tag is set then also first name image is displayed.
onerror is not working in js.
i have googled a lot coudln"t found the solution for this issue.
i have found lazy.min.js js which set src="" and data-src="pathimage"
would handled this issue.
our requirement is optimize html that why im searching for alternate solution through js.
i have found jquery link : https://api.jquery.com/error/
jQuery Ajax:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
Javascript:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Image check:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
Other:
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
HTML:
<img src="image.gif" onerror="imgError()" />
function imgError()
{
alert('The image could not be loaded.');
}
Use onerror event of HTML img tag for 2,3 and 4th scenerio. http://www.w3schools.com/jsref/event_onerror.asp
<img src="invalid_link" onerror="this.onerror=null;this.src='https://www.google.com/images/srpr/logo11w.png';" alt="">
isn't this selector is wrong:
$(".imagelazy img")
This should be either:
$("img.imagelazy")
or just image class name:
$(".imagelazy")
And also you don't have to wrap the doc ready block in any function block. and you can optimize your code like:
$('.imagelazy').attr('src', function() {
var alt1 = $(this).attr('alt').split("");
if (alt1 != '') {
var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
}
return imagepath1;
});

Javascript onclick event declation with if-else

I m newer to javascript, Now i am getting started to javascript.
Here is the link(run with example):
http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb
Here, i have raised one doubt,
if (image.src.match("bulbon")) {
//do stuff
}
May i know, what is "bulbon" why we have use?
And i tried another one example, Here is my code:
<img width="300px" height="300px" src="dim-bulb.jpg" id="bulb" onclick="changebulb()" alt=bulb"/>
<script>
function changebulb() {
var image=document.getElementById("bulb");
if(image.src.match("bulbon")) {
image.src="dim-bulb.jpg";
}
else {
image.src="bright.jpg";
}
}
When i run my code, it works partially , that is when i click, it will becomes bright, but again i click it didn't show as dim..
May i know what is my mistake?
Thanks in advance.
In your if condition
if(image.src.match("bulbon"))
you are trying to match bulbon in your gif and both the gif does not have bulbon naming.
It should be like
if(image.src.match("bulbon"))
image.src="dim-bulb.jpg";
}
else {
image.src="bulbon.jpg"; }
or check the bright image correctly like this:
if(image.src.match("bright")) {
image.src="dim-bulb.jpg";
}
else {
image.src="bright.jpg";
}
bulbon = bulb on
The code below simply checks if the image being used is the bulb with the light on and replaces the image with off version.
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
To fix your code, change it to this:
function changebulb() {
var image=document.getElementById("bulb");
if(image.src.match("bright")) {
image.src="dim-bulb.jpg";
}
else {
image.src="bright.jpg";
}
}
"bulbon" is part of the filename pic_bulbon.gif, but not pic_bulboff.gif so if(image.src.match("bulbon")) { is testing to see if the bulb is currently on.
The reason it onbly partially works is because you renamed the files - to get it working again, simply replace bulbon with bright:
<img width="300px" height="300px" src="dim-bulb.jpg" id="bulb" onclick="changebulb()" alt=bulb"/>
<script>
function changebulb() {
var image=document.getElementById("bulb");
if(image.src.match("bright")) {
image.src="dim-bulb.jpg";
}
else {
image.src="bright.jpg";
}
}
bulbon is the image name found in the src of the image tag when you see the bright light.
So when it is clicked you check the src and change the src to some other image let's say bulboff.
Your code should be like:
function changebulb() {
// get the element with id 'bulb'
var image=document.getElementById("bulb");
// check the src attribute of the image tag
if(image.src.match("dim-bulb")) {
image.src="bright.jpg"; // change the src attribute
} else {
image.src="dim-bulb.jpg"; // change the src attribute
}
}
Try this:
var image=document.getElementById("bulb");
if(image.src.match("dim-bulb")) {
image.src="bright.jpg";
}
else {
image.src="dim-bulb.jpg";
}
<img width="300px" height="300px" src="dim-bulb.jpg" id="bulb" onclick="changebulb()" alt=bulb"/>
<script>
function changebulb() {
var image=document.getElementById("bulb");
if(image.src.match("dim-bulb.jpg")) {
image.src="bright.jpg";
}
else {
image.src="dim-bulb.jpg";
}
}
</script>
I think this may be answer to your question.

Toggle images on click using jQuery

I have two images which I need to toggle on clicking on the image.
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png'
data-src='images/prof_arrow1.png' />
When the user click the image the src should get the value of data-swap and when you click again the src should change to data-src. This should keep happening just like a toggle. Any help appreciated.
$("#arrowRotate").click(function() {
var swapImage = $("#arrowGrey").attr("data-swap");
$("#arrowGrey").attr({
'src': swapImage,
id: 'arrowOrange'
});
});
This is where I have got so far.
Based on my understanding from your question, Hope this is the one you expect,
$("#arrowRotate").click(function() {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap",current);
});
DEMO Fiddle
Try This:
$("#arrowRotate").click(function(){
if($(this).attr('src')==$(this).attr('data-src'))
{
var a = $(this).attr('data-swap');
$(this).attr('src',a);
}
else
{
var b = $(this).attr('data-src');
$(this).attr('src',b);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='arrowRotate' src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg' data-swap='http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg' data-src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg'>
This might help. I think this is the simplest way of swapping between images:
<img id="arrowRotate" src="images/img1.png" data-swap="images/img2.png" data-src="images/img1.png" onclick="swapImage()" />
function swapImage(){
var swapImage = $('#arrowRotate').attr('data-swap'),
currentImage = $('#arrowRotate').attr('src');
$('#arrowRotate').attr({
'src': swapImage,
'data-swap': currentImage
});
};
If I understand you right you can do it like this:
HTML
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' data-src='images/prof_arrow1.png' data-swapped="false"/>
Javascript
$("#arrowRotate").click(function() {
var swapped = $(this).attr("data-swapped");
var init = 'false';
if(swapped === 'false'){
var swapImage = $(this).attr("data-swap");
init = true;
}else{
var swapImage = $(this).attr("data-src");
}
$(this).attr({
'src': swapImage,
'id': 'arrowOrange',
'data-swapped': init
});
});

jQuery switch image with fade

I have a script which changes some images on hover. Works really well, however I would like to add a little fade between the two images. Here is the script. Really new to jQuery so I'm a little confused where to add it. Any help would be appreciated
jQuery(document).ready(function ($) {
var img_src = "";
var new_src = "";
$(".rollover").hover(function () {
img_src = $(this).attr('src');
new_src = $(this).attr('rel');
$(this).attr('src', new_src);
$(this).attr('rel', img_src);
}, function () {
$(this).attr('src', img_src);
$(this).attr('rel', new_src);
});
//preload images
var cache = new Array();
//cycle through all rollover elements and add rollover img src to cache array
$(".rollover").each(function () {
var cacheImage = document.createElement('img');
cacheImage.src = $(this).attr('rel');
cache.push(cacheImage);
});
function imageSwitch(img) {
var src = img.attr('src');
var rel = img.attr('rel');
img.fadeOut('fast', function() {
img.attr('src', rel);
img.attr('rel', src);
img.fadeIn('fast');
});
}
$(".rollover").on('mouseenter', function() {
imageSwitch($(this));
});
a small search give me that : http://www.simonbattersby.com/demos/crossfade_demo_basic.htm i think it's kinda what you're looking for.
or else you with thread that do something also :
jQuery Change Image src with Fade Effect
it would be better to use .mouseenter for this.
and you could do .animate() opacity to 0 and in the call back you would change the image src, so that the src change after the animation ended.
$('.rollover').mouseenter(function () {
var me = $(this),
new_src = me.attr('rel'),
anmiation_duration = 300; // 300ms
me.animate({
opacity: 0
}, anmiation_duration, function () {
me.attr('src', new_src).css({'opacity':'1'});
})
});
After the src is changed you can do another .animate() to set the opacity back to 1.
I would however suggest to have the other image already displayed behind the first image, (images placed over each other using position:absolut). That way the opacity change would create sort of morf effect.
Briefly tested, thanks to #Oksid for the mouseenter comment.
EDITED
The HTML:
<img class="front rollover" src="http://placehold.it/350x150/006699" rel="http://placehold.it/350x150/000000" />
The CSS:
.image_holder {
position: relative;
}
.image_holder img {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.image_holder img.front {
z-index: 2 !important;
}
The jQuery:
function init_rollovers() {
$(".rollover").each(function() {
var w = $(this).width()+'px';
var h = $(this).height()+'px';
var src = $(this).attr('src');
var rel = $(this).attr('rel');
$(this).addClass('shown');
if (!$(this).parents('.image_holder').length) {
$(this).wrap('<div class="image_holder" style="width:'+w+';height:'+h+';"></div>');
$(this).parents('.image_holder').append('<img src="'+rel+'" />');
}
});
}
init_rollovers();
function doImageSwitch(el, speed=425) {
var front = el.find(".front");
if (front.hasClass('shown')) {
front.fadeTo(speed, 0, function() {
$(this).removeClass('shown');
});
}
else {
front.animate({
opacity: 1
}, speed, function() {
$(this).addClass('shown');
});
}
}
$(document).on('mouseenter', '.image_holder', function() {
doImageSwitch($(this));
});

hide an image in javascript using its src

I have an image defined as following:
<div id="logo" class="exhibit-flowingFacet">
<div class="wrapper">
<img src="path/to/the/image/logo.png">
</img>
</div>
</div>
I want with a javascript get the image by its src and hide it.
function hideImage() {
if (document.getElementById()
{
if (document.getElementById('logo').getElementsByClassName('wrapper').src=="path/to/the/image/logo.png")
{
document.style.visibility = 'hidden';
}
}
};
hideImage();
But the code didn't work!! any idea?
With jQuery you could write
$('img[src="path/to/the/image/logo.png"]').hide();
Try this script:
function hideImage() {
var path = 'path/to/the/image/logo.png';
var img = document.getElementById('logo').getElementsByTagName('img')[0];
if (img && img.getAttribute('src').indexOf(path) > -1) {
img.style.visibility = 'hidden';
}
}
if (window.addEventListener) {
window.addEventListener('load', hideImage, false);
} else if (window.attachEvent) { // for older IE8-6 compatibility
window.attachEvent('onload', hideImage);
}
JSFiddle
You can try this:-
$('img[src="path/to/the/image/logo.png"]').css("display","none");
or try this:-
this.style.display = "none";
getElementsByClassName('wrapper') is an array, which is why you have to access the src-attribute of the first element - at least in your case.
if (document.getElementById('logo').getElementsByClassName('wrapper')[0].src=="path/to/the/image/logo.png")
You have to make sure you have a link to jquery library in your header using this code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You could diplay:none in css if you wanted it not to render on the screen, just pass the image source into the function
function hideImage(imageSrc) {
$('img[src=" + imageSrc + "]').css("display","none");
}
and turn it back on using
$('img[src="path/to/the/image/logo.png"]').css("display","block");

Categories

Resources