jQuery change button image not working - javascript

Just learning jQuery and am using it to change the background image on a button triggered by a mouseover event. All of the console output fires at the correct times, but my image never changes. No errors are thrown. What am I doing wrong?
In the <head> element, I have this preloading script:
function preloader() {
if (document.images) {
console.log("preloading images");
contact_green = new Image();
contact_green.src = "http://www.xxxx.com/images/contact_green.png";
}
}
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);
That seems to work fine, in the sense that I get the output "preloading images". Not sure that it has the correct scope, however.
Then, in the <body> element, I have this button defined:
<td>
<button id='contact' class='CXIII' onclick="btnContact()">
<img id="logo" src="images/contact_blue.png">
</button>
</td>
Finally, I have a script that is supposed to change the image on this button upon a mouseover event:
<script>
function showHover(img) {
console.log("show hover");
if (img) img.src = contact_green;;
}
$("#contact").hover(
function () {
console.log("mouse in");
showHover(this);
},
function () {
console.log("mouse out");
}
);
</script>
I get the console output, but the image doesn't change. There are no errors thrown, either.

You are setting an object, not the source of the image
img.src = contact_green;;
needs to be
img.src = contact_green.src;
And you are not setting the image, but the button.
showHover(this);
needs to be
showHover($(this).find("img")[0]);
and since you are using jQuery
$(window).load(preloader);

Related

Mouseover and Mouseout do not work when onload process is proceeded

I have a mouseover event and a mouseout event that shows and hide images...
It works fine as long as the image is fully cached/loaded.
If I go over the image and leave the specific div (where mouseover and mouseout should trigger) fast during the load process, the mouseout event do not trigger and the image is always displayed until than (only if I reenter and leave with the cached image it works correctly). I guess that jquery is stuck in the onload process of the image and do not recognize the mouseout event. Is there any fix?
$(document).on('mouseover',".divclass", { ....
loadImage(urllink);
function loadImage(src) {
var image = new Image();
image.onload = function() {
if ('naturalHeight' in this) {
if (this.naturalHeight + this.naturalWidth === 0) {
this.onerror();
return;
}
} else if (this.width + this.height == 0) {
this.onerror();
return;
}
// At this point, there's no error. Picture is available:
$('#picture').attr('src', urllink);
$(".image-content").stop().fadeIn(200);
};
image.onerror = function() {
//display noimg.png
$('#picture').attr('src', ".../noimg.png");
$(".image-content").stop().fadeIn(200);
};
image.src = src;
}
...
});
$(document).on('mouseout',".divclass", function (e) {
$('.image-content').css("display", "none");
});
Exact the same bug happens when using mouseenter/mouseleave.
just in case someone has the same problem ...
I could not eraze the bug because jquery seems to skip the mouseout/mouseleave event when .onload for the image is going on. Furthermore a fast mouse movement increases the error rate.
I just did a small workaround:
$(document).on('mousemove', function (e) {
if ($(e.target).attr("class") !== "classname") {
$('.image-content').stop();
$('.image-content').css("display", "none");
e.stopPropagation();
} else { return; }
});
that do the trick ...

Src for the images does not set properly

I have some divs that has a class named class='tweetCon'
each containing 1 image and I want to check if the image source exist or not so if it is available I dont do anything but if not I will change the image source with an appropriate image my code is as follow:
$('.tweetimgcon').children('img').each(function () {
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
$(this).attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
and also imageExists() is as follow:
function imageExists(url, callback,callback2) {
var img = new Image();
img.onload = function() { callback(true);callback2(); };
img.onerror = function() { callback(false);callback2(); };
img.src = url;
}
now the problem is that the src for the images that are not available does not set properly though when I check the src of those images by console.log it shows that they are properly set but it is not shown and when I use inspect element of chrome I can see that src is not set . Can anyone help me?
The point is $(this) doesn't point to your object, because you call $(this) inside your imgExists callback function but NOT the jQuery callback function each, so the this object doesn't point to your original img tag!
The solution should be save the object reference first, try the below:
$('.tweetimgcon').children('img').each(function () {
var _this = $(this);
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
_this.attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
Just for a little tip for a better callback function use call.
function imageExists(url, cb, ecb) {
var img = new Image();
img.onload = function() { cb.call(img,true,url); };
img.onerror = function() { ecb.call(img,false,url); };
img.src = url;
}
I added img as the first argument and that will then be your this keyword instead of window.
Testing Bin

JavaScript changing image when hovering

I am trying to write a script, so that when someone hovers over an image, that same images changes to a different one, ie. I hover over up.png, and it changes to up_highlighted.png, when the mouse goes off the image it should change back.
However I can't seem to get it working despite all my attempts, here is the relevant code of what I have tried so far:
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up()\" onclick=\"increase_rating()\">";
function hover_up(){
$(document).ready(function() {
var oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').hover(function() {
//on hover of your element
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function() {
//when the cursor leaves your element
$('.thumbsbtn1').attr('src', oldSrc);
});
});
}
PS. I do not wish to use sprites.
Old School: http://jsfiddle.net/PAGUp/
var elem = document.getElementById('targetImg');
var oldSrc;
elem.onmouseover = function() {
oldSrc = elem.src;
elem.src = 'http://www.eclipse-developers.com/images/up_hover.png';
}
elem.onmouseout = function() {
if(typeof oldSrc !== 'undefined') {
elem.src = oldSrc;
}
}
I'm sure the jquery is more pithy. Essentially you need a variable to hold the 'old' src URL, and mouseover and mouseout handlers to set the new URL and back it out.
You don't have to wrap $(document).ready inside hover_up function. Note that I have removed onhover from HTML
Try
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onclick=\"increase_rating()\">";
$(document).ready(function() {
var oldSrc;
$(document).on('hover', '.thumbsbtn1', function () {
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function () {
$('.thumbsbtn1').attr('src', oldSrc);
});
});
try this
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up(this)\" onclick=\"increase_rating()\" onmouseout=\"hover_out(this)\">";
var oldSrc;
function hover_up(e){
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}
function hover_out(e){
$('.thumbsbtn1').attr('src',oldSrc);
}

add1 does not exist in DOM How to Add?

I am having an issue with java-script and an HTML form.
I have a form and next to the form is a button called "add" when I click add the second form appears. Next to form 2 is another button called add1, when I click this button I am wanting the third form to display. For some reason only the first add button is working.
Below is the code I have so far:
<style type="text/css">
#newservicesetup1, #newservicesetup2 {
display:none;
}
</style>
<script type="text/javascript">
function showform(theform) {
var showHides = new Array('newservicesetup1','newservicesetup2');
for (i=0;i<showHides.length;i++) {
document.getElementById(showHides[i]).style.display=
(document.getElementById(showHides[i]).id == theform) ? 'block' : 'none';
}
}
function loadBehaviors () {
if (document.getElementById) {
document.getElementById('add').onclick = function() { showform('newservicesetup1'); }
document.getElementById('add1').onclick = function() { showform('newservicesetup2'); }
}
}
window.onload = loadBehaviors;
</script>
Try adding a semicolon to the end of the assignments:
function loadBehaviors () {
if (document.getElementById) {
document.getElementById('add').onclick = function() { showform('newservicesetup1'); };
document.getElementById('add1').onclick = function() { showform('newservicesetup2'); };
}
}
You can check your Javascript for syntax using Online Javascript Lint.
why not just
document.getElementById('add').onclick = function() {
document.getElementById('newservicesetup1').style.display = 'block';
}
document.getElementById('add1').onclick = function() {
document.getElementById('newservicesetup1').style.display = 'block';
}
that will show the correct forms when you click the appropriate button. if you want them to disappear when clicking again, you will only need a slight modification
When loadBehaviors() is called, add1 does not exist in the DOM yet. Bind to the event handler after you add it to the DOM.

JavaScript image at onload event

I am trying to load a new image every time the previously loaded image has finished loading.
The function create_photo_list works correctly. It creates an array of the photos that need to be loaded. If none need to be loaded then the array is empty. The problem is, when there are no more items to load the it keeps calling the load_next_photo function.
The reason I call the registerEventHandler every time in the function is because if I don't, the function is not called when the next photo loads.
function registerEventHandler(node, event, handler) {
if (typeof node.addEventListener == "function")
node.addEventListener(event, handler, false);
else
node.attachEvent("on" + event, handler);
}
// Remove an HTML element event handler such as onclick
// ex: unregisterEventHandler($("textfield"), "keypress", showEvent);
function unregisterEventHandler(node, event, handler) {
if (typeof node.removeEventListener == "function")
node.removeEventListener(event, handler, false);
else
node.detachEvent("on" + event, handler);
}
function load_next_photo() {
var loading_list = create_photo_list();
alert(loading_list.length);
if (loading_list.length > 0) {
img[loading_list[0]]['loaded'] = 1;
registerEventHandler($("load_img"), "onload", load_next_photo());
$("load_img").src = img[loading_list[0]]['img'];
}
else {
alert("nothing");
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
Can't get my head around what you currently have, but such code works just fine:
var _images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var _index = 0;
window.onload = function() {
LoadImage();
};
function LoadImage() {
//stop condition:
if (_index >= _images.length)
return false;
var url = _images[_index];
var img = new Image();
img.src = url;
img.onload = function() {
_index++;
LoadImage();
};
document.getElementById("Container").appendChild(img);
}
This will add the images to the container (element with ID Container) one by one, live test case: http://jsfiddle.net/yahavbr/vkQQ7/
This is plain JS, feel free to ask about any part for elaboration. :)

Categories

Resources