user2490003
user2490003

Reputation: 11890

How to conditionally display HTML based on the page URL

I have a few different web pages -

www.foo.com/index.html
www.foo.com/dog.html
www.foo.com/cat.html

Assume the pages are very similar, except for an image and some text in the middle of the page that's unique to that page.

I have an external script that dynamically creates the HTML for each page using templates and substituting in various variables and configurations. I'm trying to figure out how to display a certain piece of HTML only for a certain page (e.g. cat.html)

In psuedo-code, this is what I'd like to do -

  <style>
    function isCatPage() {
      if page.url.contains("cat.html")
        return true;
      else
        return false;
      end
    }
  </style>

  if isCatPage {
  <bold>This text only appears on cat.html</bold>
  }

  <p> This is random dynamically generated HTML</p>
</body>

Using basic javascript to show <bold> on an specific HTML page.

Thanks!

Upvotes: 1

Views: 6082

Answers (2)

Ted
Ted

Reputation: 4057

I would use jquery and do something like the following:

<script type='text/javascript'>
    // only run this when the page finishes loading
    $(document).ready(function () {
        // if cat.html exists in the url
        if (window.location.href.indexOf('cat.html') > -1) {
            // select the p by its id and hide it or - 
            $('#conditional').css('visibility', 'visible');
        }
        else {
            // show it
            $('#conditional').css('visibility', 'hidden');
        }
    });
</script>

<p id='conditional'>This text only appears on cat.html</p>
<p>This is random dynamically generated HTML</p>

Upvotes: 3

Andrei Nemes
Andrei Nemes

Reputation: 3122

Get the current url, and split it

var url_parts = location.href.split(/\//g);
var page = url_parts[url_parts.length-1];

page should contain the current page (eg cat.html)

Although, I'd really suggest you use a server for this kind of stuff

Upvotes: 1

Related Questions