Andrei Daniel
Andrei Daniel

Reputation: 181

Building a small page with an image with 3 buttons

I want to build a small webpage with 3 buttons, like this, with a background image: enter image description here

By hovering on one of the buttons, the image should change using js.

What would be the best way to achieve this effect? I tried with background-image, but when the image changes it doesn't change instantly. It first makes the page white, I don't know why.

Thanks.

///edit:

   document.addEventListener("DOMContentLoaded", function()
   {
    document.querySelector(".gaming").addEventListener("mouseover", function()
    {
        document.querySelector(".container").style.backgroundImage = 'url(1.png)';
    });
    document.querySelector(".media").addEventListener("mouseover", function()
    {
        document.querySelector(".container").style.backgroundImage = 'url(2.png)';
    });
    document.querySelector(".forum").addEventListener("mouseover", function()
    {
        document.querySelector(".container").style.backgroundImage = 'url(3.png)';
    });  
   });
   
.container {
    position: relative;
    height: 1080px;
}

.gaming 
{
position: absolute;
height:100%;
}

.media
{

}

.forum {
    position: absolute;

}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Portal</title>
    <script src="js.js"></script>
    <link rel="stylesheet" type="text/css" href="css.css">
    <link rel="stylesheet" type="text/css" href="reset.css">
  </head>
  <body>
<div class="container">
  <image class="image-portal"></image>
  <a class="gaming">1</a>
  <a class="media">2</a>
  <a class="forum">3</a>
</div>
  </body>
</html>

That's how I tried to do it. Now I'm trying to position the buttons. Should I change the image src instead of adding a backgroundImage? (also I think I need a handler for mouseleave too).

Upvotes: 1

Views: 109

Answers (2)

Pluto
Pluto

Reputation: 3026

You can download the images in advance without any code, just place some <link rel="preload"> tags in the header like so:

<head>
    <link rel="preload" href="1.png" as="image" type="image/png" />
    <link rel="preload" href="2.png" as="image" type="image/png" />
    <link rel="preload" href="3.png" as="image" type="image/png" />
</head>

Additional information: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

Upvotes: 1

Yaky Refael
Yaky Refael

Reputation: 166

I think you should load the images when you init the page. You can create an array and then load the images from this array..

Upvotes: 0

Related Questions