0

I found this code on another post on how to create a popup box with a button but I would like to change the button to a custom image. I would really appreciate if somone could help me with this.

Here is the code on JSFIddle: http://jsfiddle.net/j4c7U/

Javascript:

window.onload = function() {
  document.getElementById("LearnMoreBtn").onclick = function(){
        var overlay = document.getElementById("overlay");
        var popup = document.getElementById("popup");
        overlay.style.display = "block";
        popup.style.display = "block";
    };

  document.getElementById("CloseBtn").onclick = function(){
        var overlay = document.getElementById("overlay");
        var popup = document.getElementById("popup");
        overlay.style.display = "none";
        popup.style.display = "none";      
  }
};

CSS

#overlay {
    display:none;    
    position:fixed;  
    left:0px;        
    top:0px;         
    width:100%;      
    height:100%;     
    background:#000; 
    opacity:0.5;     
    z-index:99999;   
}

#popup {
    display:none;
    position:fixed;
    left:50%;        
    top:50%;         
    width:300px;     
    height:150px;
    margin-top:-75px;
    margin-left:-150px;
    background:#FFFFFF;
    border:2px solid #000;
    z-index:100000;      
}

HTML

<button id="LearnMoreBtn">Learn More</button>
<div id="overlay"></div>
<div id="popup">
    Popup contents here
    <button id="CloseBtn">ClosePopup</button>
</div>
<div>
    some other content that will be behind the popup
</div>
user3167464
  • 19
  • 1
  • 7

1 Answers1

0

The quickest way to achieve what you're asking for is to change the <button> to an <img>, but retain the id so as to not interrupt the JavaScript.

from:

<button id="LearnMoreBtn">Learn More</button>

to:

<img src="https://www.google.com/images/srpr/logo11w.png" width="269" height="95" id="LearnMoreBtn" />

Here's an updated JSFiddle, with the Google logo as the image: http://jsfiddle.net/k3zw2/1/

Replace the src of the Google logo to your custom image and voila! :)

  • Alright, that worked thanks! Btw, I just realized that if I have more than one of those HTML codes, only the first one will open the popup, the others won't, is is possible to fix that too? – user3167464 Jan 14 '14 at 00:20
  • The reason for this is because the code uses IDs, and you can only have one ID per page. You could technically make double and triple copies of the JS code to compensate, but that could get really hairy really fast. How many popups were you thinking of having? If quite a few, instead of having separate popup links (LearnMoreBtn) and popups per instance, you could instead have the contents of the popup change depending on which "LearnMoreBtn" is selected. – modenadude Jan 14 '14 at 00:33