0

I'm trying to get an image to display in a div depending on the URL of the page. This div is in an include file that gets used for all pages of the website. What I want is if it's the homepage (with or without index.php), is for the div to show the image. What I've pieced together so far is:

<script type="text/javascript">
var d = location.href

if (d="website.com" || "website.com/index.php") 
{
<img src="/images/DSLogo2.jpg" />;
}
</script>

I'm not sure if this is correct, or even the best way to go about it. Any help is very greatly appreciated, as I am still learning more and more each day.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
wanderboy
  • 1
  • 1

3 Answers3

0

Do not confuse = and == operator. The correct way how to code the condition is

if (d=="website.com" || d=="website.com/index.php")

Javascript is not a preprocessor, you can't usi it to create the code like in PHP. If you want to add element, you have to work with DOM:

<div id="target"></div>
<script>
  var d = location.href;
  var target = document.getElementById("target");
  if (d=="website.com" || d=="website.com/index.php") {
    target.innerHTML = '<img src="/images/DSLogo2.jpg"/>';
  }
</script>
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
0

Try:

<script type="text/javascript">
var d = window.location.href

if (d="website.com" || "website.com/index.php") 
{
    document.write('<img src="/images/DSLogo2.jpg" />');
}
</script>
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
-1

JavaScript doesn't work that way. You could use document.write with logic like that but something like this would be better:

if (your logic here) {
    var image = document.getElementById('my_image');
    image.src = 'some_image.jpg';
}

Notice that assumes you'll have a unique id on your image element. You'll want to put this logic in the document ready event or window on load.

davidethell
  • 11,708
  • 6
  • 43
  • 63