Traffic lights, simple jquery class changing

Traffic lights, simple jquery class changing
0.0 0

#1

@randelldawson i will be really grateful if you find some time ans teach me how do I shorten this jquery.
And why am i facing problems while trying to change classes using javascript instead of jquery .the code


#2

Can you explain what you want to happen when the various buttons are clicked and then explain what is happening instead?


#3

@Lelouch it’s happening exactly as I want, but if possible, I want to know a shorter way to do it.
and I searched for the way to use javascript to change CSS classes, using class list , or something close, but it did not work.


#4

Using jQuery and some simplifications/modifications to the HTML and CSS, you can do:

HTML

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
        <title>Traffic lights</title>
    </head>
    <body>
        <div class="light lightred" id ="mydiv"></div>
        <button class="start" data-color="lightgreen">start traffic</button><br/>
        <button class="alert" data-color="lightyellow">Get ready</button>
        <button class="stop" data-color="lightred">stop traffic</button>
    </body>
</html>

CSS

body {
    background-color:black;
}

.light {
    margin:50px;
    width:200px;
    height:200px;
    border-radius:50%;
}

.lightred{
    background-color:red;
    box-shadow:
    1px 1px 50px red,
    1px -1px 50px red,
    -1px 1px 50px red,
    -1px -1px 50px red;
}

.lightyellow{
    background-color:yellow;
    box-shadow:
    1px 1px 50px yellow,
    1px -1px 50px yellow,
    -1px 1px 50px yellow,
    -1px -1px 50px yellow;
}

.lightgreen{
    background-color:green;
    box-shadow:
    1px 1px 50px green,
    1px -1px 50px green,
    -1px 1px 50px green,
    -1px -1px 50px green;
}

button {
    border-radius:50px;
    font-size:30px;
    font-weight:bold;
    margin:20px;
}

.start{
    background-color:rgba(0,255,0,1);
    border:2px solid rgba(0,255,0,1);
}

.stop{
    background-color:rgba(255,0,0,1);
    border:2px solid rgba(255,0,0,1);
}

.alert{
    background-color:rgba(255,255,0,1);
    border:2px solid rgba(255,255,0,1);
    padding-left:15px;
    padding-right:15px;
}

JavaScript

$(function(){
    $('button').click(function(){
        $('#mydiv').removeClass().addClass('light ' + $(this).data('color'));
    });
});