Home » Web Design and Development » Javascript » How to hide code / Div based on contents in URL using JavaScript ?

How to hide code / Div based on contents in URL using JavaScript ?

There are some reasons where you want certain button / image to be hidden for some section of URL’s. For example, we are showing “Publish New Ad” button on one of our website which is visible for all URL’s of a website, and same also becomes visible on “publish-new.html” html page which is opened once user clicks on that button.

But since the user is already on “publish-new.html” page, there is no point in showing the same button again to user, so we wanted to hide this button only on URL which contains string “publish-new”. We achieved this with following Javascript code,

URL = window.location.href;
if (!URL.includes("publish-new")) {
button_html = "<a href=\"https://www.greenecosystem.in/fconn/publish-new.html\" style=\"position:fixed;bottom:10px; left: 35%; right: 35%; width: 30%;\"> <button type=\"button\" class=\"btn btn-primary btn-sm\" style=\"background-color:#2f9d17;\"> <b> Post Free Ad </b></button></a>";
document.getElementById("hide_publish_button").innerHTML = button_html;
<p id="hide_publish_button"></p>

As you can see above, we used “window.location.href” to know what is the current URL and then with “!URL.includes(“publish-new”)” code, we decided to show buttons only when the URL doesn’t included “publish-new” and hence “Publish New” button will gets hidden for “publish-new.html”

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment