zbora23
zbora23

Reputation: 151

Change CSS style on button click?

I would like to change some of css style properties on div element when I click button, but I don't have that much experience nor I can find anything online to help me. At the present moment this is how my code looks like.

<button class="button1">Click</button>
<div class="popup_middle">
</div>
<div class="grayout">
</div>

and my CSS looks like this

.grayout {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    z-index: 99;
    visibility: hidden;
    background-color: #000;
    filter: alpha(opacity = 55);
    opacity:.80;
}

.popup_middle{
    position: fixed;
    background: url(../images/bg-food-order.jpg);
    border: none;
    top: 50%;
    left: 50%;
    width: 350px;
    height: 250px;
    margin-top: -125px;
    margin-left: -175px;
    z-index: 100;
    visibility: hidden;
}

Please could you pleas give me some advice or code sample with JS that is going to solve my problem.

Thanks in Advance , David

Upvotes: 5

Views: 39623

Answers (3)

Alireza moghaddam
Alireza moghaddam

Reputation: 9

so if you want to add css class style to a text using a button:=>

          <script>
            function changed(){
            document.getElementById("exp").classList.add("the class style name")};
          </Script>
              <div id="exp">
                <button onclick=" changed()">try it</button>
                <p onclick="changed()">hello world</p>

              </div>

Upvotes: 1

stackErr
stackErr

Reputation: 4170

You use getElementById which will look for elements with an id. The div you are looking for has a class but no id. So when you run the code you have, nothing happens because the javascript cant find any element with an id of popup_middle.

To fix this you can change the div to have an Id of popup_middle and your CSS should have #popup_middle.

HTML:

<button onClick="document.getElementById('popup_middle').style.visibility='visible';">Cli‌ck</button>
<div id="popup_middle"></div>
<div class="grayout"></div>

CSS:

.grayout {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    z-index: 99;
    visibility: hidden;
    background-color: #000;
    filter: alpha(opacity=55);
    opacity:.80;
}
#popup_middle {
    position: fixed;
    background: green;
    border: none;
    top: 50%;
    left: 50%;
    width: 350px;
    height: 250px;
    margin-top: -125px;
    margin-left: -175px;
    z-index: 100;
    visibility: hidden;
}

fiddle: http://jsfiddle.net/eLJYZ/2/

Upvotes: 0

Thomas Taylor
Thomas Taylor

Reputation: 555

Something like

<script type='text/javascript'>

$('.button1').click(function() { $('.popup_middle').hide().css('color', 'blue'); });

</script>

Would hide that popup_middle div and set the text color to blue when you clicked on the button. click() is the event handler

Upvotes: 4

Related Questions