Dankata Dankata - 8 months ago 28
Javascript Question

jQuery - Trigger element when enters div

I am trying to develop a script where the header clones as soon as it enters the targeted div without using the function fromTop. Thank you:)

$(document).ready(function() {
var $header = $(".header"),
$clone = $header.before($header.clone().addClass("clone"));

$(window).on("scroll", function() {
var fromTop = $(window).scrollTop();
$("body").toggleClass("down", (fromTop > 490));

I have also made a jsFiddle - https://jsfiddle.net/Lng9cf7v/2/


This code finds the current distance between the navbar and the div where you want the navbar to be cloned. Once the distance between the two are 0px or less (navbar is on top or below the div), the navbar is then displayed by adding the .down class. toggleClass() was causing jitteriness with the navbar, so I used addClass() and removeClass() instead.

$(window).on("scroll", function() {

    var cloneArea = $('.other-div').offset().top;
    var fromTop = $(window).scrollTop();

    if ((fromTop - cloneArea >= 0) && ($("body").hasClass("down") == false)) {


    } else if ((fromTop - cloneArea < 0) && ($("body").hasClass("down") == true)) {




working demo: https://jsfiddle.net/kkdaily/rp0dhvuv/