Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript If statment in slider function to loop to start?

  • This topic is empty.
Viewing 11 posts - 1 through 11 (of 11 total)
  • Author
    Posts
  • #194245
    porgeet
    Participant

    Hey guys and girls

    I’m new to web development and I’m currently going through the interactive website tutorial on codecademy.

    I’ve got this chunk of code – it works – but I’m not sure why. It’s for an image slider, the if statement’s position in the block of code if puzzling me.

    var main = function() {
        $('.dropdown-toggle').click(function(){
            $('.dropdown-menu').toggle();
        });
        $('.arrow-next').click(function(){
            if(nextSlide.length == 0) {
      nextSlide = $('.slide').first();
      nextDot = $('.dot').first();
    }
            var currentSlide = $('.active-slide');
            var nextSlide = currentSlide.next();
    
    `currentDot = $('.active-dot');
        nextDot = currentDot.next();
        currentDot.removeClass('active-dot');
        nextDot.addClass('active-dot');
        currentSlide.fadeOut(600).removeClass('active-slide');
        nextSlide.fadeIn(600).addClass('active-slide');
    });
    
    };
    
    $(document).ready(main);
    

    If I define the if statement after I declare the nextSlide and nextDot variables it doesn’t work. Can anyone help me clarify why it wouldn’t? Just so I know how JS works in a bit more detail.

    Thanks a lot
    porgeet

    EDIT

    It appears there may be a bug in codecademy that causes you to have to juggle code around to proceed to the next lesson as the above JS now doesn’t work.

    I thought it shouldn’t as those variables in the if statement haven’t been defined yet. I take it JS reads top to bottom?

    ANOTHER EDIT

    I’m aware the above code I hadn’t used var to define the currentDot and nextDot variables, but for some reason it worked. Honestly, I think codecademy has a few bugs as I’ve just completed the course with the following code, but it doesn’t actually do what it’s meant to in the preview window ie. the .dot is a dot that shows the current sliders position in the DOM and should loop back to the first and last when it’s reached those points, but it doesn’t. Is my code sound? Don’t want to be learning the wrong thing :P

    var main = function() {
        $('.dropdown-toggle').click(function(){
            $('.dropdown-menu').toggle();
        });
    
        $('.arrow-next').click(function(){
    
            var currentSlide = $('.active-slide');
            var nextSlide = currentSlide.next();
    
            if(nextSlide.length == 0) {
                nextSlide = $('.slide').first();
                nextDot = $('.dot').first();
            }
    
            var currentDot = $('.active-dot');
            var nextDot = currentDot.next();
    
            currentDot.removeClass('active-dot');
            nextDot.addClass('active-dot');
    
            currentSlide.fadeOut(600).removeClass('active-slide');
            nextSlide.fadeIn(600).addClass('active-slide');
        });
    
        $('.arrow-prev').click(function(){
            var currentSlide = $('.active-slide');
            var prevSlide = currentSlide.prev();
    
            if(prevSlide.length == 0) {
                prevSlide = $('.slide').last();
                prevDot = $('.dot').last();
            }
    
            var currentDot = $('.active-dot');
            var prevDot = currentDot.prev();
    
            currentDot.removeClass('active-dot');
            prevDot.addClass('active-dot');
    
            currentSlide.fadeOut(600).removeClass('active-slide');
            prevSlide.fadeIn(600).addClass('active-slide');
        });
    
    };
    
    $(document).ready(main);
    
    #194265
    shaneisme
    Participant

    Do me a favor and put your full code and markup into CodePen so we can take a look. Reviewing code is one thing, but seeing it work (or not) is another.

    You’ve made two edits to the above post, but I’m not sure what you do and do not still need help with. So if you could set up the pen + clarify what you need help with I’d be happy to see what’s what.

    #194312
    porgeet
    Participant

    Hi shaneisme

    Thanks for taking the time to respond. I’ll set one up and populate it with the code at lunchtime.

    Thanks again
    porgeet

    #194337
    porgeet
    Participant

    Ok, don’t mean to bumb.

    Here’s a codepen from the codecademy JS course.

    http://codepen.io/porgeet/pen/myMdyJ

    It works fine. I think it’s just codecademy funking up.

    As far as I can tell, JS reads top to bottom and executes in that manner is that right?

    Also, if you have any other useful resources that you would recommend for a beginner web developer I’d really appreciate it (lessons, tools like Sublime etc.)

    Many thanks
    porgeet

    #194341
    Shikkediel
    Participant

    I started the course at Codeacademy at some point (not very long ago) too but after getting to know some basics, I think most can be learned from creating a website and finding solutions to whatever idea of dynamic (inter)action you might come up with.

    As far as I can tell, JS reads top to bottom and executes in that manner is that right?

    Well… yes and no. Some methods are synchronous (they will ‘wait’ on each other) and some are not (they will fire simultaneously). The lines will be read top to bottom but the methods will not necessarily trigger in that way time-wise. Then there are other tools like looping, queueing and callbacks to influence the order in which the function runs.

    As far as I know, that is. I consider myself a rookie still. Nowhere near the 10k hours yet to refer to any ‘expertise’…

    #194357
    shaneisme
    Participant

    I might do something more like this:

    http://codepen.io/drainpip/pen/gbxbXz

    Lookup DRY (Don’t Repeat Yourself). I’m taking all the repetitive stuff and putting it into a function called getSlides(). All the slides can be set up any time you wish.

    I’m also returning it as an object, hence the slides.currentSlide... syntax.

    Note, I’m also using the .on() method instead of .click() as it is recommended in the spec. That normally means the old one will eventually be depreciated. Using .on() has more flexibility as well. You can do something like:

    $(element).on('click touchstart`, function() {
      // stuff in here fires for click or touchstart
    });
    

    More on .on(): http://api.jquery.com/on/

    #194464
    porgeet
    Participant

    Thanks guys


    @Shikkediel
    Thank you, I thought that might be the case, I bumbed into that concept when declaring if statements before variables to try and get round codecademy bugging out.


    @shaneisme
    Thanks, I really wasn’t expecting that much :D

    I get the DRY premise, I watched Chris’ Modern Web Designer’s Workflow presentation. I’m so new that I’m not even aware I could/would need to reuse that code.

    I have one question based on what you’ve done and one that came up from really examining the code to while trying and figure out what you did.

    1. Why do you need to return an object? I take it the slides.currentSlide line selects the getSlider() function then the currentSlide variable within the function? Or is it selecting the returned object? I don’t know what ‘returning’ an object is or does yet, I’m just not sure why you need to do it if the above line references the currentSlide variable.
    2. In the if statements it checks if both the prevSlide and nextSlide variables are equal to 0. Now is this referencing the DOM order? 0 being the end of available HTML elements within that selection and it would depend if you are moving .next() or .prev(). 0 for .next() would be slide 4 and 0 for .prev() would actually be slide number 1?

    I hope that makes sense. I don’t want to pester you with annoying questions, I just couldn’t find any explanation for my questions that I could yet understand in the jQuery or w3Schools documentation.

    Thanks again
    porgeet

    #194476
    shaneisme
    Participant

    I returned an object because I wanted to send back all of the variables. A function can only return once, as soon as it has returned something it exits, even if there’s more code further down.

    So I could just return each variable by itself. I could have also done it with an array, but I prefer the object notation of object.item, it’s just more clear to me.

    This line gets whatever is returned inside the function and sets it equal to a variable: var slides = getSlides();. Now, that variable is equal to everything in the return statement of that function. Since that’s the case, var slides is the object.

    If you were to put in code that said console.log(slides); after it was declared, you’d see it in the console of the browser (in dev tools). Maybe that would be good so you can visualize it.

    Both .prev() and .next() are jQuery methods. They look for the next/previous sibling in the DOM. If one isn’t found, it will have a .length of 0, not the variable itself – it’s still a jQuery object at that point.

    Your last question is partially correct. If you’re on the first slide, slides.nextSlide is set to the first $('slide') jQuery object, not just 1 or 4. If you set something to a jQuery object, then you can manipulate it with jQuery in many ways.

    Read up on tree traversal in jQuery: http://api.jquery.com/category/traversing/tree-traversal/

    Don’t worry about pestering me or any of us, we love to help those that genuinely want it.

    #194477
    shaneisme
    Participant

    One thing that might not be clear to you, that I just thought of, is scope.

    You might be wondering, “Well, if the variables are declared in that function, why do we bother returning them?” The answer is scope. Inside a function, with a variable declared, those variables are not accessible outside the function. You can only get stuff that’s in the same scope or “above”.

    For instance:

    var foo = 'bar';
    
    function zing() {
      return foo;
    }
    
    console.log(zing());
    

    This will show “bar” in the console.

    But this:

    function foo() {
      var bar = 3;
    }
    
    function zing() {
      return bar;
    }
    
    console.log(zing());
    

    This will return undefined because function zing() has no idea what the variable bar is.

    More: http://www.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

    #195849
    porgeet
    Participant

    Hey shaneisme

    Thanks a lot for all your explanations they’ve really helped. Sorry it’s been so long responding to your help, I’ve been busy learning! :) Supplementing what you’ve said with some more courses and some w3Schools.

    Here is what I understand about the way you did it and why.

    1. A function contains more than just data types, as opposed to variables and objects. So that contains the meaty bits of the slider. The actions.
    2. The variables used within the function are local and as such can only be accessed within the ‘scope’ of that function (ie’ inside the {}).

    3. You can access objects from outside a function hence why you made them equal to the function’s local variables.

    4. You made the slides variable equal to the function so you could use the object dot notation like this to select specific elements within the getSlides(); function slides.currentSlide.fadeOut(600).removeClass('active-slide');

    Question: In the above code, using the dot notation. Say you had more than one object inside another, could you put something like object.key1.key2.key3.fadeOut(600).removeClass('some-class');?

    Thanks a lot for all your help again, I hope I got a lot of that right or near enough :D

    Cheers
    porgeet

    #195862
    shaneisme
    Participant

    https://www.youtube.com/watch?v=AAJaWFdgeVM

    1. In my example, the function `getSlides()` is collecting a bunch of jQuery objects and returning them. And of course if it can’t find the first/last ones it adjusts accordingly. A function, any function that is, can do whatever you want. It’s best practice to only do one tiny thing though, that makes it easier to maintain long-term. Even my example might be a bit too much for one function to do to some people.
    2. Correct, as long as you’re talking about the function’s brackets and not the object it’s returning.
    3. Whatever you return is what the function is going to be equal to once it’s called. You can return the number 2 and add the function call to 1 to get 3.
    4. I made the `slides` variable equal to what `getSlides()` was returning – an object filled with objects. Once I have that object filled with objects set equal to `slides`, I can then manipulate it by targeting what I need. You should try adding `console.log(slides);` after the variable has been declared and then open up devtools console to see what it’s like.
Viewing 11 posts - 1 through 11 (of 11 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.