settingsAccountsettings
Menusettings

Q: Link Buttons (task with DOM and jQuery)

+2 votes

You are given HTML holding some buttons. Implement the attachEvents function which should attach click events on the buttons. When a button is clicked it should remove the class="selected" attribute from the button that currently holds it and add it to its own attributes. Use the attachEventListener function.

HTML, CSS and JavaScript Code - You are given the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="link-buttons.css" />
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="link-buttons.js"></script>
</head>
<body onload="attachEvents()">
    <a class="button">Sofia</a>
    <a class="button">Plovdiv</a>
    <a class="button">Varna</a>
</body>
</html>

CSS File:

a.button {
    border: 1px solid #CCC;
    background: #EEE;
    padding: 5px 10px;
    border-radius: 5px;
    color: #333;
    text-decoration: none;
    display: inline-block;
    margin: 5px;
}

a.button.selected {
    color: #111;
    font-weight: bold;
    border: 1px solid #AAA;
    background: #BBB;
}

a.button.selected::before {
    content: "\2713\20\20";
}

a:hover {
    cursor: pointer;
}

Example:

link buttons jquery task

asked in JavaScript category by user Jolie Ann

1 Answer

+1 vote

The HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="link-buttons.css">
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <script src="link-buttons.js"></script>
    <!--<script src="src/jquery-3.2.1.min.js"></script>-->
</head>
<body onload="attachEvents()">
<a class="button">Sofia</a>
<a class="button">Plovdiv</a>
<a class="button">Varna</a>
</body>

</html>

CSS file:

a.button {
    border: 1px solid #CCC;
    background: #EEE;
    padding: 5px 10px;
    border-radius: 5px;
    color: #333;
    text-decoration: none;
    display: inline-block;
    margin: 5px;
}

a.button.selected {
    color: #111;
    font-weight: bold;
    border: 1px solid #AAA;
    background: #BBB;
}

a.button.selected::before {
    content: "\2713\20\20";
}

a:hover {
    cursor: pointer;
}

JavaScript file with the jQuery code inside:

function attachEvents() {
    $("a.button").on("click", buttonClicked);

    function buttonClicked() {
        $(".selected").removeClass("selected");
        $(this).addClass("selected");
    }
}
answered by user matthew44
...