Matt
Matt

Reputation: 173

show content on specific page javascript

I am trying to show a div element on a specific page e.g. - example.com/my-account , right now it is showing on all my-account pages for example - example.com/my-account/lost-password

I know how to use JavaScript but not in webpages so can someone help me? This is how I would do it with JavaScript. I just need someone to help get this to work inside the php page I am trying to edit.

<script>
var cx = window.location;
var curWin = String(cx);
var myAccount = "http://example.com/my-account/";

if (curWin == myAccount){
<div id="banner"><img src="http://img.c5454o.png"></div>
}

</script>

Upvotes: 0

Views: 227

Answers (3)

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

If you open your developer tool, you can see that the body is assigned with classes (when using <body <?php body_class(); ?>>).

For example <body class="home page page-id-7 page-template-default">.

So from here on, you can tell css what to do like so:

#banner {display: none;}
body.page-id-7 #banner {display: block;}

So you don't realy need Javascript to detect a specific page and display a specific element.

Upvotes: 1

Zeeshan
Zeeshan

Reputation: 117

if you want to show a div element on specific page then create a unique id on that page like <div id='UniqueId'> then go to javascript code and write,

jQuery Code is:

if($('#UniqueId').length > 0)
{
 //show specific element

 }

Upvotes: 0

danish farhaj
danish farhaj

Reputation: 1354

Add Your condition like this

var cx = window.location;

if(cx.substr(-11)=="my-account/") {
   //then do whatever you want
}

OR if your string is without last slash then..

if(cx.substr(-10)=="my-account") {
   //then do whatever you want
}

substr(-11) function will cut your string of url from last 10 indexes so you can apply your contion then.

Upvotes: 0

Related Questions