This is purely for learning purposes; I know that CSS would be the preferred method for this situation.
I know that in JavaScript, you can use inline event handling to hover over an image, like so:
<img src="image.png" onMouseover="src='image2.png'" onMouseout="src='image.png'">
And I know you can install jQuery in your site, and do the following code or similar:
HTML:
<img src="image.png" id="image-hover">
jQuery:
$(document).ready(function() {
$( "#hover-example" ).mouseover(function(){
$(this).attr("src", "image-hover.png");
});
$( "#hover-example" ).mouseout(function(){
$(this).attr("src", "image.png");
});
});
I was wondering how one would use JavaScript-only to produce that output, but use an external script instead of inline event handling. I've tried browsing through various Stack Overflow and Google searches, but mostly they lead to using jQuery instead. Could it be that complicated to apply that simple inline JavaScript to an external script?
Thanks!
var image = document.getElementById("hover-example");
image.onmouseover = function() { image.src = "image-hover.png"; }
image.onmouseout = function() { image.src = "image.png"; }
Pretty much the same way
var img = document.getElementById('image-hover');
img.addEventListener('mouseenter', function() {
this.src = 'image-hover.png';
}, false);
img.addEventListener('mouseleave', function() {
this.src = 'image.png';
}, false);
Since you're interested in a vanilla JavaScript implementation, take a look at the documentation for the mouseover event.
You can achieve your desired result by doing something like this:
var img = document.getElementById('image-hover');
img.addEventListener('mouseenter', function() {
this.src = 'image-hover.png';
}, false);
img.addEventListener('mouseleave', function() {
this.src = 'image.png';
}, false);
Related
I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.
$img = $('#picture');
function bubbleOnLoad() {
$(document).ready(function() {
$img.load(function(){
alert('document loaded')
$('#left-bubble').show();
})
})
The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within my init function. Can someone explain to me why nothing is working?
function choosePic()
$('.speechbubble').hide();
$('#picture').remove();
var randomNum = Math.floor(Math.random() * samplePics.length);
var img = new Image();
img.onload = function() {
$('.playing-field').prepend(img);
handleImageLoad();
}
img.src = samplePics[randomNum];
img.id = "picture";
}
var samplePics =
"assets/images/barack-obama.jpg",
"assets/images/donald-trump_3.jpg",
"assets/images/dt-2.jpg",
"assets/images/bill-clinton.jpg",
"assets/images/Rose-Byrne.jpg",
"assets/images/pic.jpeg",
"assets/images/priest.jpg",
"assets/images/tb.jpg",
"assets/images/test.jpg",
"assets/images/amy-poehler.jpg",
"assets/images/stephen-colbert.jpg",
"assets/images/aziz-ansari.jpg"
];
You had some syntax errors in your code which I corrected and came up with this:
function bubbleOnLoad() {
$img = $('#picture');
$img.load(function () {
alert('document loaded');
$('#left-bubble').show();
});
}
$(document).ready(function () {
bubbleOnLoad();
});
Here is the JSFiddle demo
In you code you are not even telling the browser it's supposed to run a code after image load. you should do something like this:
$(function(){
// DOM Content is ready, let's interact with it.
$('#picture').attr('src', 'image.jpg').load(function() {
// run code
alert('Image Loaded');
});
});
Also according to docs a common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
Try this jQuery plugin waitForImages
https://github.com/alexanderdickson/waitForImages
//Javascript/jQuery
$(document).ready(function(){
var counter = 0,totalImages= $('#preloader').find('img').length;
$('#preloader').find('img').waitForImages(function() {
//fires for all images waiting for the last one.
if (++counter == totalImages) {
$('#preloader').hide();
yourCallBack();
}
});
});
/*css*/
#preloader{
position:absolute;
top:-100px;/*dont put in DOM*/
}
#preloader > img{
width:1px;
height:1px;
}
<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
<!--HTML [after body start] -->
<div id=preloader>
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.png" />
<img src="4.gif" />
<img src="5.jpg" />
</div>
You can only access the HTML element after it was created in DOM.
Also you need to check if the image was loaded before showing.
Thus your code need to look something as below:
$(document).ready(function() {
bubbleOnLoad();
});
function bubbleOnLoad() {
var newSrc = "https://lh5.googleusercontent.com/-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
$img = $('#picture');
$img.attr('src', newSrc) //Set the source so it begins fetching
.each(function() {
if(this.complete) {
alert('image loaded')
$('#left-bubble').show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
<img id="picture"/>
</div>
I have a problem to combine to functions in one onclick button. This is how my product have to look like: I want to put a hammer down when I click on an invisible button, when the hammer reaches an icon, the icon has te become another picture.
This is the code I have, but it's in javascript and jquery:
$('.box hammer').on('click', function() {
$(this).toggleClass('clicked');
});
function changeImage1() {
var image = document.getElementById('safari');
if (image.src.match("bulbon")) {
image.src = "safari.png";
} else {
image.src = "safariflat.png";
}
}
You can bind multiple on handlers to the same element and event, that's not a problem.
Delaying one of those handlers can be done in many ways, how is up to you. Libraries like Underscore and lodash offer a number of delay types, such as debounce.
You should be able to use something like:
function immediateHandler() {
alert("Immediate handler!");
}
function lateHandlerImpl() {
alert("Late handler!");
}
var lateHandler = _.delay(lateHandlerImpl, 2500);
$('div.button').on('click', immediateHandler);
$('div.button').on('click', lateHandler);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click Me!</div>
Replace the alerts with your logic (creating/switching the images) and change the timing to sync the image changes up, and you should be able to create a fairly convincing animation.
You could use setTimeout for this:
$('.box hammer').on('click', function() {
$(this).toggleClass('clicked');
setTimeout(function() {
changeImage1();
// change time below to the time your animation takes
}, 5000);
});
function changeImage1() {
var image = document.getElementById('safari');
if (image.src.match("bulbon")) {
image.src = "safari.png";
} else {
image.src = "safariflat.png";
}
}
I am trying to make my jquery codes look better here. My functions are working correctly but I was wondering if anyone can make my codes less ugly. Thanks a lot!
HTML
<div class='image_layout'>
<a href='#'><img src=' a.jpg '/></a>
<br><p class='credits'>hahahah
<br>Agency: Agency1
<br>Picture ID: 5 </p>
</div>
jQuery
$('#image_layout').on('hover', 'img', function() {
$(this).parent().next().next().fadeIn('fast');
})
$('#image_layout').on('mouseout', 'img', function() {
$(this).parent().next().next().fadeOut('fast');
})
You can pass two functions to jQuery hover - one for mousein, one for mouseout. You can make this change as long as you don't have dynamically added images. Your code would also be a lot simpler if the element you are fading has an ID or class:
$('#image_layout img').hover(
function () {
$(this).closest('.someClass').fadeIn('fast');
},
function () {
$(this).closest('.someClass').fadeOut('fast');
}
);
$('.image_layout').on('hover', 'img', function (e) {
if(e.type == 'mouseover') {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
} else {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
}
})
You could also have done:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
}, function() {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
});
If you're sure that nothing other than hovering the image will cause the element to fade, you could simply write:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeToggle('fast');
});
Look into Douglas Crockford's JS Style Guide. He'd make your code look something like (with improvements):
var obj = $('#image_layout img');
obj.mouseover( function(){
$(this).parent([selector]).next([selector]).fadeIn('fast');
});
obj.mouseout( function(){
$(this).parent([selector]).next([selector]).fadeOut('fast');
});
You don't need the on, just call the function directly.
I would use .eq as opposed to two next statements, additionally, hover takes two functions, the first being for the mouseenter event, and the second for mouseout
$('#image_layout').hover('hover', 'img', function () {
$(this).parent().eq(2).fadeIn('fast');
}, function () {
$(this).parent().eq(2).fadeOut('fast');
})
References
Take a look at eq here
Read over hover here
I have written code like this. <img id='test_img' src='../../..' />
I want to get the id of this image on image load like,
$(img).load(function() {
// Here I want to get image id i.e. test_img
});
Can you please help me?
Thanks.
$(img).load(function() {
var id = $(this).attr("id");
//etc
});
good luck!!
edit:
//suggested by the others (most efficient)
var id = this.id;
//or if you want to keep using the object
var $img = $(this);
var id = $img.attr("id")
Don't use $(this).attr('id'), it's taking the long, inefficient route. Just this.id is necessary and it avoids re-wrapping the element with jQuery and the execution of the attr() function (which maps to the property anyway!).
$(img).load(function() {
alert(this.id);
});
$(function() {
$('img#test_img').bind('load', function() {
console.log(this.id); //console.log($(this).attr('id'));
});
});
$(img).load(function() {
alert($(this).attr('id'));
});
I have the following markup with inline javascript and would like to change it to Jquery. Any help would be appreciated.
<a title="823557" href="/PhotoGallery.asp?ProductCode=471823557" id="product_photo_zoom_url">
<img border="0" onload="vZoom.add(this, '/v/vspfiles/photos/471823557-2.jpg');"
alt="823557"
src="/v/vspfiles/photos/471823557-2T.jpg" id="product_photo"></a>
I guess I would need to use this?
$(function(){
<---- somecode---->
});
$(function () {
$("#product_photo").load(function (e) {
vZoom.add(this, this.src.replace('T.', '.'));
})
})();
If $ doesn't work for some reason, this should also work. I incorporated Kranu's advice since that library most likely only needs the DOM loaded as a prerequisite, rather than the load event:
jQuery(function ($) {
$("#product_photo").each(function () { // in case there is more than one
vZoom.add(this, this.src.replace('T.', '.'));
});
});
Note that there is no need to put a separate bind event on the img because the $(function() { }) waits until the body loads.
$(function(){
vZoom.add(document.getElementById('product_photo'),'/v/vspfiles/photos/471823557-2.jpg');
});
Not exactly sure what you are trying to do, but essentially you would remove the image from the HTML and dynamically load it using JS. Once loaded, you would inject it in the DOM and set the onload event.
var jsImg = new Image();
jsImg.onload = function(){
vZoom.add(this,'/v/vspfiles/photos/471823557-2.jpg');
var img = document.createElement('IMG');
img.setAttribute('id','product_photo');
img.setAttribute('alt','823557');
img.setAttribute('src','/v/vspfiles/photos/471823557-2T.jpg');
img.style.border = 'none';
//inject image now in the DOM whereever you want.
};
jsImg.src = '/v/vspfiles/photos/471823557-2T.jpg';