Lukas Baliƫnas Lukas Baliƫnas - 3 months ago 7
Javascript Question

Event when a pair of elements are clicked

I have 5 elements with class

.home
and unique id's, and a button with class
.btn1
. When
.home
is clicked after
.btn1
and vice versa, a function should be executed. I don't know what jQuery method i should use.

Answer

Try this :

<!DOCTYPE html>
<html>
<head>
    <style>
        .active {
            background-color: skyblue;
        }
    </style>
</head>
    <body>
        <div class="home">I am Div1</div>
        <div class="home">I am Div2</div>
        <div class="home">I am Div3</div>
        <div class="home">I am Div4</div>
        <div class="home">I am Div5</div>
        <button class="btn">Run</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            var divReady = false;
            var btnReady = false;
            $(".btn").on("click",function(){
                btnReady = true;
                $(this).addClass("active");
                if (divReady)
                    fun();
            })
            $("div").on("click",function(){
                divReady = true;
                $("div").removeClass("active");
                $(this).addClass("active");
                if (btnReady)
                    fun();
            })
            
            function fun() {
                alert("I am working!")
                $(".btn,div").removeClass("active");
                btnReady = false;
                divReady = false;
            }
            
        })
    </script>
    </body>
</html>
        

Comments