I wrote an inline script to automatically handle when a browser can not load an SVG and replace it with a PNG image. This part works great, however I also want to change the image onhover and this answer worked great for me except that I don't need it to "run and find" if the browser can handle SVG and doesn't use the PNGs. So, I thought I would have it trigger when a class of noSVG (herein referred to as "myclass") was added to the IMG tags.
Now here's were the issues start, I can use CSS to modify the style of the class which is added. But I can't use jQuery to modify it. Even stranger, when I went to add it to JSFiddle for you guys, it works. Before you guys think that I'm using a bad version of jQuery I tested multiple versions (including 1.10.1 which is use by JSFiddle).
HTML:
<img src="1.svg" onerror="this.onerror=null; this.src='1.png'; this.className+=' myclass';" class="image" id="1" />
jQuery:
$(function() {
$(".myclass")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "hover.png";
$(this).attr("src", src);
//console.log("moused over");
})
.mouseout(function() {
var src = $(this).attr("src").replace("hover.png", ".png");
$(this).attr("src", src);
//console.log("moused out");
});
});
JSFiddle
You are adding the class myclass dynamically to the image, so you need to use event delegation
$(function () {
$(document).on('mouseover', ".myclass", function () {
var src = $(this).attr("src").replace('.png', 'hover.png');
$(this).attr("src", src);
//console.log("moused over");
}).on('mouseout', ".myclass", function () {
var src = $(this).attr("src").replace("hover.png", ".png");
$(this).attr("src", src);
//console.log("moused out");
});
});
Demo: Fiddle
Related
I have this code in my js file and basically what I want to test out is, if the user clicks on a certain button (which has ID of admin).
I want it to bring up a closeButton which is png image and then when the user clicks this again it should disappear. To test of the button functions are responsive I have put alerts in the functions.
Clicking on the initial button works, the function finds the corresponding ID, makes the alert("jQuery Worked") line and brings up the closeButton image.
However when I click on the close button nothing happens (we expect here that the alert("hiii") would work but it doesn't. I have looked online and found that my code needed to be in a $(document).ready(function() {} function which it is but it isn't working. I also tried to use the ID of the image to make the closeButton image disappear but that didn't work either. So I have tried just using the $closeButton variable which I thought for usre should work but doesn't. Why?
.js file
var $closeButton = $("<img>");
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'> </div>");
var $closeButton = $("<img class='classMe' id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
});
$closeButton.click(function() {
alert("hiiii");
});
});
you looking for Event delegation.
Event delegation refers to the process of using event propagation
(bubbling) to handle events at a higher level in the DOM than the
element on which the event originated. It allows us to attach a single
event listener for elements that exist now or in the future. Inside
the Event Handling Function.
$(document).on('click', '#closeButtonID', function() {
alert('hiii');
});
Do this:
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'></div>");
var $closeButton = $("<img id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
});
$(document).on('click', '#closeButtonID', function() {
alert('hi');
});
});
Not a good way to do this but it's a different way to solve the problem , Hope it will help you :
var $closeButton = $("<img>");
$(document).ready(function() {
$("#admin").click(function (event) {
var $overlay = $("<div id='overlay'> </div>");
var $closeButton = $("<img class='classMe' id='closeButtonID' src='https://s23.postimg.org/ouup1ib6z/close_button.png'></img>");
$("body").append($overlay);
$overlay.append($closeButton);
alert("jQuery worked");
close();
});
function close(){
$('#closeButtonID').click(function() {
alert("hiiii");
});
}
});
JSFIDDLE
I'm doing some testing with working and broken images:
HTML:
<img src="http://asdf.com/working.jpg" />
<img src="http://asdf.com/broken.jpg" /> <!-- non valid URL -->
jQuery:
$('a').click(function() {
$(this).find('img').error(function() {
alert('Image does not exist!');
});
return false;
});
This works to an extent... Basically I want it to alert ONLY if the user clicks on the broken image. What am I doing wrong?
I would bind to the image for error events, then add the alert logic if there was an error.
Here's a working JSFiddle example I created.
$( "img" ).error(function() {
$( this ).click(function() {
alert('Image does not exist!');
});
});
The error() method was deprecated in jQuery 1.8. So you should be using on('error',function(){}); instead. But, you still have the issue where the error handler has to be attached before the image load is attempted. So, you can set the img src after you attach the handler.
EDIT: It was bothering me that I didn't have a src in my img tag (invalid HTML), so I found this inspired stack overflow: What's the valid way to include an image with no src?. The src="//:0" is from there.
HTML:
<img data-src="http://placekitten.com/300/300" src="//:0" />
<img data-src="http://asdf.com/broken.jpg" src="//:0" />
<!-- non valid URL -->
Javascript
$(document).ready(function () {
$('img').on ('error', function () {
$(this).data('error',true);
}).each(function() {
$(this).attr('src',$(this).data('src'));
});
$('a').click(function () {
if($(this).find('img').data('error') == true) alert('Image does not exist!');
return false;
});
});
http://jsfiddle.net/10xjo3of/2/
You could use onerror attribute for images. the following compatibility table lists the browsers that support the onerror attribute and you can see that you can use this without any issue:
http://www.quirksmode.org/dom/events/error.html
Add onerror="$(this).addClass('error');" to images like this:
<img src="http://asdf.com/working.jpg" onerror="$(this).addClass('error');" />
<img src="http://asdf.com/broken.jpg" onerror="$(this).addClass('error');" /> <!-- non valid URL -->
And on every click, check the error class:
$('a').click(function() {
if ($(this).find('img').hasClass('error')){
alert('Image does not exist!');
}
});
JSFiddle Demo
I'm trying to have a CSS link disabled for 1 second after it has been clicked.
I have tried this without success;
In the header:
<script type="text/javascript">
$(function() {
$("#link").click(function() {
$("#link").attr("disabled", "disabled");
setTimeout(function() {
$("#link").removeAttr("disabled");
}, 2000);
});
});
</script>
Html:
the link text
CSS:
.link:diabled {
some values here.. }
You have a class="link", but with $("#link") you are addressing the id called link.
So write $(".link") everywhere instead of $("#link").
By the way: with .link:disabled you won't address the link as this only works on inputs and buttons. If you need to address it, use .link[disabled="disabled"] { ... } or even better add a class to it called disabled_link and then do in CSS .disabled_link { ... }.
There are quite a few problems here:
You are using # (the ID selector), but your html is using classes.
<a> does not have a disabled attribute
If it did, you would probably want to use .prop instead of .attr
If you change code to use classes, $(".link").prop("disabled", true) would affect all anchors, so you should probably use this.
Because disabled does not exist for <a>, the :disabled selector does not seem to work for CSS.
A working solution would be something like this:
$(".link").click(function() {
var $this = $(this);
$this.addClass('disabled');
setTimeout(function() {
$this.removeClass('disabled');
}, 2000);
});
$(document).on('click', '.disabled', function (e) {
e.preventDefault();
});
http://jsfiddle.net/ExplosionPIlls/PaYcc/
'link' is a class and you are using it as ID. Do $('.link') instead of $('#link').
I think this approach works better. The other allows you to click the link multiple times and mess up the setTimeout this unbinds the event and then re-attaches the event after the setTimeout ex: double click the link
$(".link").click(linkBind);
function linkBind(){
var $this = $(this);
$this.addClass('disabled');
$this.unbind('click');
setTimeout(function() {
$this.removeClass('disabled');
$this.bind('click', linkBind);
}, 2000);
}
$(document).on('click', '.disabled', function (e) {
e.preventDefault();
});
http://jsfiddle.net/PaYcc/1/
I want to replace an image with another using jQuery in JavaScript. Its an online bus reservation website. So when clicked on an available image it should change into unavailable image. Does anyone know about this.
You can do something like this:
$('#myImage').on('click', function(e) {
var image = this;
img.src = '/path/to/another/image.png';
});
Also, if you have a bunch of images that need to be swapped, it's better to use event delegation. Let's assume that these swappable images can be anywhere on the page, and you assign a swappable class to all of them. You can then set up just one event handler to handle the swapping, even if you dynamically add new images with AJAX:
$(document).on('click', 'img.swappable', function(e) {
var image = this;
image.src = getAvailableImageUrl();
});
There are lots of ways, Here are some.
<img id="bannerLogo" src="/path/to/image/logoup.png" />
<script type="text/javascript">
var imageCounter = 0;
$('#bannerLogo').click(function(){
if(imageCounter%2==0){
$('#bannerLogo').attr('src', '/path/to/image/logodown.png');
}
else {
$('#bannerLogo').attr('src', '/path/to/image/logoup.png');
}
imageCounter++;
});
</script>
Or
(Note - As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().)
<img class="swapper" src="imagename_off.jpg" />
<script type="text/javascript">
$(function(){
$(".swapper").live('click', function() {
if ($(this).attr("class") == "swapper") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
</script>
I hope this helps.
Ill also add in my hover script, just in case you need it at some point:
$('#bannerLogo').hover(
function() { $('#bannerLogo').attr('src', '/path/logodown.png');},
function() { $('#bannerLogo').attr('src', '/path/logoup.png');
});
Don't forget to include JQuery lib
http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js
Thanks,
Philip
I'm at a bit of a problem with jQuery and an image.
I'm trying to create a simple system where an image changes on hover (which I've successfully made work with jQuery .hover()) however I'm now trying to set it up so if the user clicks on the image, the source is permanently changed to the hover image.
The problem I'm having is when I click, the source changes but when I hover off it changes back to the "off" image! Such a simple problem but I can't find a solution.
The hover code:
$("#image").hover(function () {
$(this).attr("src", getImageSourceOn("image"));
}, function () {
$(this).attr("src", getImageSourceOff("image"));
});
The functions getImageSourceOn / Off simply return a string based on the parameter with the new source.
The onClick code:
var imageSource = $(imageID).attr("src");
var onOff = imageSource.substring((imageSource.length - 5), (imageSource.length - 4));
if (onOff == "F")
{
//alert("Off\nstrID = " + strID);
$(imageID).attr("src", getImageSourceOn(strID));
}
else
{
//alert("On");
$(imageID).attr("src", getImageSourceOff(strID));
}
This code just takes the source and looks for On / Off within the source to put the opposite as the image. I tried using .toggle() instead of this substring method but I couldn't get it to work.
Declare a global variable. Attach a function on the click event:
var clicked = false;
$("#image").click(function(){
if(!clicked)
clicked = true;
else
$(this).attr("src", getImageSourceOff("image"));
});
Then modify you hover code
$("#image").hover(function () {
$(this).attr("src", getImageSourceOn("image"));
}, function () {
if(!clicked)
$(this).attr("src", getImageSourceOff("image"));
});