Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Making functions to pass styles parameters 1

Status
Not open for further replies.

lupidol

Programmer
Apr 23, 2008
125
0
0
IL
Hi everyone
Attached is my code where I want background image of a div to be selected by js:
Code:
<!DOCTYPE html>

<html lang = "en">
<head>
  <title>to-forum.html</title>
  <meta charset="utf-8" />
  <style>
  .logo 
  {
    width:1200px;
    height:300px;
    margin:auto;
    display: block; 
    background-repeat:no-repeat;
    position:relative;
    border-radius: 25px;
  }
  </style>
    <script>
      function ChangeImage(param)
      { 
        switch(param)
        {
          case '1':
            return("images/greensilver.gif");
            break;
          case'2':				
            return("images/greensilver1.gif");
            break;
        }
      }
    </script>
</head>

<body>
  <div id="logo"> 
    <script>
      document.getElementByClassName("logo").style.backgroundImage = "url('" + ChangeImage('1') + "')";
    </script>
  </div>
</body>
</html>
The image doesn't show up ! Could anyone correct my js code ?
Thanks
 
Hi

Have you declared that getElementByClassName method somewhere ?

Because the DOM has only [tt]getElement[red]s[/red]ByClassName()[/tt] method. Which returns [tt]HTMLCollection[/tt].

BTW, since [tt]querySelector()[/tt] is pretty well supported, personally I prefer that :
JavaScript:
document[teal].[/teal][COLOR=darkorange yellow]querySelector[/color][teal]([/teal][i][green]"[highlight].[/highlight]logo"[/green][/i][teal]).[/teal]style[teal].[/teal]backgroundImage [teal]=[/teal] [i][green]"url('"[/green][/i] [teal]+[/teal] [COLOR=orange]ChangeImage[/color][teal]([/teal][i][green]'1'[/green][/i][teal]) +[/teal] [i][green]"')"[/green][/i][teal];[/teal]
But of course, not with the HTML you posted as there is no logo [tt]class[/tt].

Feherke.
feherke.github.io
 
Thanks a lot feherke. You are very helpful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top