Pandemum
Pandemum

Reputation: 53

Load javascript into div when user scroll position reaches it

I want to make the script load into the div only when user reaches it. I am trying to accomplish this using jQuery, but no success. Maybe you can help. Here is the code:

var scrollFromTop = $("#float_div_id").offset().top;

$(document).scroll(function () {
    if ($(this).scrollTop() > scrollFromTop) {
        var s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.src = 'javascript code src which i want to append on scroll';
        document.getElementById('float_div_id').appendChild(s);
    }
});

Upvotes: 2

Views: 4227

Answers (2)

sebastienbarbier
sebastienbarbier

Reputation: 6832

You should give a look at waypoint library. It trigger an event when user scroll on a specific element and them you can execute some coding (tempting ?)

var waypoint = new Waypoint({
  element: document.getElementById('thing'),
  handler: function(direction) {
    alert('You have scrolled to a thing')
  }
})

Then after scrolling, you should use $.getScript() with a separate JS file :

Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.

$.getScript('/javascript/myscript.js');

And be careful about using asynchronous if some code require your new js file :

$.getScript('/javascript/myscript.js', function() {
    // do something here
});

let me know if this work for you :D

Upvotes: 0

Pramod Karandikar
Pramod Karandikar

Reputation: 5329

In your case, $(this).scrollTop() would be coming out to be lesser than scrollFromTop.

Change your if condition to this and try again :

if ($(this).scrollTop() + $(window).height()  > scrollFromTop)

Upvotes: 1

Related Questions