简体   繁体   中英

jQuery Hide/Show DIV on change of anchor text

I have one page website which changes URL #id or anchor text on scrolling and on navigation click. I have an image positioned fixed at the center of the site. The site is divided in different sections and the image shows in all the sections. I do not want to show the image on the first section as it is unrelated to the content of the 1st section but will be showed in all next sections. How can I make it work?

What I have tried till now but not working:

$(document).ready(function(){
    $(".phone").hide();
    var idSample = window.location.href.split("#");
    var id = "#"+idSample[1];
    if($(id) == "second"){
        $(".phone").show();
    }else{
        $(".phone").hide();
    }
});

Rest in Fiddle: https://jsfiddle.net/shubhamjha1000/vh7bu32q/

I don't want that phone to be seen on 1st section but on rest of the sections. Please help me guys!

You can use the answer written in this question to listen to changes in the window see what url you are on and show or hide the phone accordingly....

Example:

    $(function(){

  // Bind the event.
  $(window).hashchange(hashchanged);

  // Trigger the event (useful on page load).
  hashchanged();

});

function hashchanged(){
 var hash = location.hash.replace( /^#/, '' );
 //your code
 if(hash == "#first") {
    // Hide element
  } else {
    // Show element
  } 
}

But still even though what you are planning to do will work with that solution I think it would still look bad on the app it self and instead of a hovering phone maybe you can create the phone as an img inside the relevant containers and hide and show with id...

You can simply use a substring on your location.hash for get your hash tag

$(document).ready(function(){
    $(".phone").hide();

    var id = window.location.hash.substr(1);

    if($(id) == "second"){
        $(".phone").show();
    }else{
        $(".phone").hide();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM