Search code examples
javascripthtmlmobilegetelementbyid

JavaScript getElementById not working on mobilephone


I'm creating a website which has some JavaScript code. Everything of that JavaScript is working fine on the computer. But on my iPhone 7 the getElementById function does not work. I try to set a source of an img tag but nothing happens.

JavaScript:

var header_bar = $('.js-header-bar, .js-header-bar-mobile');
var header_bar_mobile = $('.js-header-bar-mobile');
var header_bar_navbar = header_bar_mobile.find('.navbar-primary');
var header_bar_toggler = header_bar_mobile.find('.navbar-toggler');
var header_bar_offsetTop =  header_bar.offset().top;

$(window).on('scroll', onScroll); 
function onScroll(){
    if ($(this).scrollTop() > header_bar_offsetTop){
        header_bar.addClass("sticky");
        document.getElementById("headerLogo").src = "images/logo-black.png";


    } else {
        header_bar.removeClass("sticky");
        document.getElementById('headerLogo').src = "images/logo-white.png";
    }
}

The function should add at the top of the site a black logo and if I scroll a white logo. On the computer it works but on my smartphone not.

HTML:

<header class="header header-mobile js-header-bar-mobile d-md-none">
    <div class="header-bar">
        <div class="header-bar-logo">
            <a href="index.html">
                <img class="originalTest" alt='Auto mit Schriftzug: "Autohandel-ZAR"' id="headerLogo" src="images/logo-white.png"/>
            </a>
        </div>
        <div class="header-bar-menu">
            <button class="navbar-toggler hamburger" type="button" id="js-header-toggle">
                <span class="hamburger-box">
                    <span class="hamburger-inner"></span>
                </span>
            </button>
        </div>
    </div>

Thank you in advance.


Solution

  • I solved the problem by getting the element with jQuery by class and not by Id so the issue was the Id part.

    Working Code:

    function onScroll(){
        if ($(this).scrollTop() > header_bar_offsetTop){
            header_bar.addClass("sticky");
            $(".logoHeader").attr("src", "images/logo-black.png");
    
    
        } else {
            header_bar.removeClass("sticky");
            $(".logoHeader").attr("src", "images/logo-white.png");
        }
    }