offset () and position () - jquery

1

I have the following problem.

In Firefox, when using the property .position() , it is always relative to the position of the browser window, that is, it makes the position of the window never reach the position of the element, because it increases the position top said element. Instead, with Chrome this happens.

I thought about using the .offset() property, but this does not get me the actual position of the element (it does not get the margins, so it's always below the actual position).

var menu;
var windowPosition = 0;

/* Secciones donde el menú debe ser negro */
var box1;
var box1Inicio = 0;
var box1Fin = 0;

var imgMenu;

$(window).load(function() {
    menu = $(".menu");
    if( $("#box-text-1").length ) {
        box1 = $("#box-text-1");
        box1Inicio = box1.offset().top; //Aquí es donde probé ambos métodos
        box1Fin = box1Inicio + box1.outerHeight(true);
    }
});

$(window).scroll(function() {
    windowPosition = $(this).scrollTop();

    if( windowPosition >= box1Inicio && windowPosition <= box1Fin ) {
        imgMenu = menu.find(".menu-button").find("img").attr("data-black");
    }
    else {
        imgMenu = menu.find(".menu-button").find("img").attr("data-white");
    }
    menu.find(".menu-button img").attr("src", imgMenu);
});

This code basically checks the top position of the browser, and if it is between those "start" and "end", it changes the menu image.

The HTML would be something like this:

<div class="seccion1">
    ...
</div>
<div class="seccion2" id="box-text-1">
    ...
</div>
<div class="seccion3">
    ...
</div>

Each section with its padding 's and margin s. As I mentioned above, the offset() property does not get these attributes, but with position() in Firefox it is always changing the values of top .

Any solutions that you can apply to this problem?

Edit: I add JSFiddle

    
asked by Cheshire 29.11.2016 в 12:59
source

1 answer

2
  

The error is that in Firefox when scrolling the function that modifies the src of the image is not executed.

Try to make the following modification.

Replace this:

    $(window).scroll(function() {

Because of this:

    $(window).on('scroll', function() {
    
answered by 29.11.2016 / 15:17
source