Search code examples
jqueryhtmlslidetoggleunderline

Underline active link slideToggle (jQuery)


I made a text page where information pops up when the user clicks on a link using slideToggle().

When you click on the next link, the previous text passage automatically closes (also using slideToggle).

jQuery(document).ready(function() {
    jQuery('.textbox a').next('.textbox p').hide();
    jQuery('.textbox a').click(function() {
        $('.active').not(this).toggleClass('active').next('.textbox p').slideToggle();
        $(this).toggleClass('active').next().slideToggle();
    });
});
.textbox {
    width: 50px;
    text-align: center;
    float: left;
}

.textbox a {
    cursor: pointer;
}
<div id="textbox1" class="textbox">
    <a>Link1</a>
    <p>Text that is toggled.</p>
</div>
<div id="textbox2" class="textbox">
    <a>Link2</a>
    <p>Text that is toggled.</p>
</div>
<div id="textbox3" class="textbox">
    <a>Link3</a>
    <p>Text that is toggled.</p>
</div>
<div id="textbox4" class="textbox">
    <a>Link4</a>
    <p>Text that is toggled.</p>
</div>

How can I get the active "link" underlined? I have tried several things but the closest I could get was that every link was underlined once a single one was active.


Solution

  • You could use CSS text-decoration:underline;.

    Whatever you do in CSS, as long as you apply it to the .active class, it will be applied only to the active link.

    jQuery(document).ready(function() {
        jQuery(".textbox a").next(".textbox p").hide();
        jQuery(".textbox a").click(function() {
            $('.active').not(this).toggleClass('active').next('.textbox p').slideToggle();
            $(this).toggleClass('active').next().slideToggle();
        });
    });
    .textbox{           width: 50px;
                        text-align: center;
                        float: left;}
    
    .textbox a{         cursor: pointer;}
    /* This is the only line you need to add: */
    /* Or you could use border-bottom:1px solid black; instead. */
    .active {text-decoration:underline;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <div id="textbox1" class="textbox">
        <a>Link1</a><p>Text that is toggled.</p>
    </div>
    <div id="textbox2" class="textbox">
        <a>Link2</a><p>Text that is toggled.</p>
    </div>
    <div id="textboxe" class="textbox">
        <a>Link3</a><p>Text that is toggled.</p>
    </div>
    <div id="textbox4" class="textbox">
        <a>Link4</a><p>Text that is toggled.</p>
    </div>