mhsc90
mhsc90

Reputation: 374

Javascript ScrollTo anchor

Hello guys I have a problem with the javascript (i m not a big fan of this language :)). So I would like on my website an automatic Scroll : i have four div,which one has the same height (depends on the size of your screen). I want when i scroll to the bottom (or the top) that the slider goes directly to the next div (or previous), like a magnet. So I tried the scrollTo but i don t know how it works because i have to listen the scroll... so here is my html:

<!--Samsung Galaxy-->
    <div  class="bloc" id="samsungtab">
        <img src="images/samsung.png" alt="samsunggalaxytab" />
    </div>

<!--ORA-->
    <div class="bloc" id="ora">
        <img src="images/ora.png" alt="logo" />    
    </div>

<!--Oculus Rift-->
    <div class="bloc" id="oculus">
        <img src="images/oculus.jpg" alt="logo" />
    </div>

<!--Acer-->
    <div class="bloc" id="acer">
        <img src="images/acer.jpg" alt="logo" />                
    </div>

and the javascript for the automatic size of the different div:

$(document).ready( function(){
    var hauteur = (document.documentElement.clientHeight);
    var position = hauteur/4;
    $(".bloc").css("height",hauteur);
    $("#samsungtab").css("margin-top",position);
    $("#ora").css("margin-top",position);
    $("#oculus").css("margin-top",position);
    $("#acer").css("margin-top",position);
});

Thank you very much in advance for your help!!!!

Tom

Upvotes: 0

Views: 1414

Answers (1)

Gerben van Dijk
Gerben van Dijk

Reputation: 878

To me it seems like you are looking for something like this:

https://github.com/peachananr/onepage-scroll (demo here: http://www.thepetedesign.com/demos/onepage_scroll_demo.html)

I would advise you to use this jQuery plugin (based on the JS code in your example you are using jQuery).

If you'd like to code it yourself, you should start by rewriting your CSS. Setting the height of the .block elements via JS should not be necessary, but it depends on how the rest of your HTML is built up. If you add the complete HTML file here I might be able to assist on this as well.

After that you should look into jQuery's .scroll() handler. Usage:

$(window).scroll(function(){

   //code that runs on scroll here

})

Another useful jQuery function in this case is .offset(). You can get the coordinates (so as well the distance from the top) of any visible element like this:

$('.block').offset().top.

Lastly, you should look into jQuery's .scrollTop() function. You can use this function to get the current scroll position: $(document).scrollTop(), or to set the desired scroll position:

$(document).scrollTop(200)

Good luck, I hope it helps!

Upvotes: 2

Related Questions