Reputation: 37
I have a module that I created however given specific project guidelines Ive been forced to use Javascript instead of completing the project purely with CSS/HTML.
Simply put when the user hovers over one of the LI elements in the nav bar, an image must be updated to reflect the newly hovered nav element. Each of these LI elements has a data attribute attached to it that is used to update the img src on hover using this JS code:
$jq(".flexUL li").hover(function () {
// Changes the .bigImg src to the src defined in flexUL li data attributes.
var value = $jq(this).attr("data-src");
var thisUrl = $jq(this).attr("data-url");
$jq("#bigImage img").attr("src", value);
$jq("#bigImage a").attr("href", thisUrl);
});
Pls ignore the jq. THats something necessary for our internal development. Its regular jquery.
The issue is that sometimes on the hover there is a noticeable lag between the time when the cursor moves over the LI element and when the img src updates to match the data attribute on the li element.
One of the project constraints seemingly prevents me from just using css hovers, as I was required to make the updated image src stay while the user hovered on an li element then moved the cursor away from said element.
Again, my ultimate question is, after looking at my code and seeing its intended purpose; Might there be a faster way to accomplish the job? As it is currently there will sometimes be a noticeable lag time.
Any help is loved and appreciated!
Upvotes: 0
Views: 699
Reputation: 15847
I would loop through your li
items first and preload
each image. That way when they are finally called, the images will have already been loaded.
$jq(document).ready(function(){
$jq(".flexUL li").each(function () {
img = new Image();
img.src = $jq(this).attr("data-src");
});
});
Upvotes: 1
Reputation: 4435
In your initial jquery code that runs on document ready, add this code to preload your images. You should get rid of the delay by doing this.
img = new Image();
img.src = "http://domain.tld/path/to/image.jpg";
Upvotes: 0