0

Im following Jeffrey ways excellent learn jquery in 30 days on youtube, but I cant get the slider to work using his code. which stems down to the imgWidth variable not being set correctly when the variables are set at the top of the script.

images = sliderUL.find('img'),                    
    imagesLen = images.length,
    current = 1,
    imgWidth = images[0].width; // giving 0 instead of 600??

It gets 0, However if I console.log the images[0].width further down the script when a button is clicked it shows the correct value of 600. Its as if the dom isn't ready at the time of the first assignment or it does the assignment before the images width is known? can somebody tell me whats going on? I tried wrapping the whole thing in a document ready function just in case that was the issue, but it still doesn't work

full demo here

Paul 501
  • 707
  • 7
  • 14

3 Answers3

1

You have to wait until the image is loaded. Have a look at this answer:

jQuery width() and height() return 0 for img element

EDIT:

For completeness:

images.on('load',function(){
    imgWidth = $(this).width();
    console.log(imgWidth);
    totalImgsWidth = imagesLen * imgWidth;
});
Community
  • 1
  • 1
chrisg86
  • 11,548
  • 2
  • 16
  • 30
  • The only issue I have now, is I seam to be creating 2 global variables, but if I use var imgWidth then its not accessible outside that on load function? how do we get around that please? – Paul 501 Mar 18 '16 at 09:09
  • Whatever you want to has to be moved inside the load callback. Otherwise you do not have access to the image width. – chrisg86 Mar 18 '16 at 09:16
0

You're using an older jquery version. Use the google hosted version 2.2.0 or later at https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js.

You can check your own code, literaly nothing changed but the jquery on:

https://jsfiddle.net/Aschab/jh8s4meo/

Working and superb

As a good practice this:

jQuery(document).ready(function(){
(function($){

Is redundant, try:

 jQuery(document).ready(function($){

Just my 2 cents

Aschab
  • 1,378
  • 2
  • 14
  • 31
  • changing jquery version to 2.2.0 on codepen does not make it work :( – Paul 501 Mar 18 '16 at 08:00
  • But the same code is working on jsfiddle. Which means is not the code, is codepen. Both codepen and jsfiddle are emulators, but i've got some uncatchable errors on both. I recomend you to try it on localhost. – Aschab Mar 18 '16 at 08:03
0
images.on('load',function(){
        imgWidth = $(this).width();
        console.log(imgWidth);
        totalImgsWidth = imagesLen * imgWidth;
    });

This fixed the issue, as pointed out by user2968356

Paul 501
  • 707
  • 7
  • 14