Search code examples
jqueryonclickthishiddenelement

Show hidden elements


I have a question about jquery code below because I dont fully understand how it works. I would like to know how javascript knows that when I click on the first ahref with class showMore it only unhides exactly the first hidden element with class hiddenSpan and the same when I click on the second element, JS unhides exactly second hidden element. Both elements have the same hiddenSpan classes so how these elements are recognized ?

HTML

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<div class="container flex our-people clearfix">
<div class="tile">
   <h4>Peter Bolton - Partner</h4>
   <img src="img.jpg" />
   <p>Peter Bolton lives in Burnley with his wife and two children.<span class="hiddenSpan">Peter was admitted as a solicitor in May 1975, having completed two years Articles with a Blackburn firm of solicitors.</span><a href="#" class="showMore">Show more</a></p>
   <a href="mailto:" class="btn">Send email <i class="fa fa-caret-right" aria-hidden="true"></i></a>
</div>
<div class="tile">
   <h4>Peter Bolton - Partner</h4>
   <img src="img.jpg" />
   <p>Peter Bolton lives in Burnley with his wife and two children.<span class="hiddenSpan">Peter was admitted as a solicitor in May 1975, having completed two years Articles with a Blackburn firm of solicitors.</span><a href="#" class="showMore">Show more</a></p>
   <a href="mailto:" class="btn">Send email <i class="fa fa-caret-right" aria-hidden="true"></i></a>
</div>
</div>
<script src="script.js"> </script>
</body>
</html>

JavaScript

(function($) {

$(".hiddenSpan").hide();

$(document).ready(function() {

    $(".showMore").on("click", function(e) {

        e.preventDefault();

        var $this = $(this),
            content = $this.prev();

        if(content.is(":hidden")) {
            content.slideDown(700);
            $this.text("Show less");
        } else {
            content.slideUp();
            $this.text("Show more");
        }

    });
});

})(jQuery);

Solution

  • $(".showMore").on("click", function(e) {//this is clicking the class
    
        e.preventDefault();
    
        var $this = $(this),//as there is more than one with same class 'this' is referancing the clicke done
            content = $this.prev();//here he gets the previous element of the clicked one
    
        if(content.is(":hidden")) {//asks if it is hidden or no
            content.slideDown(700);//if hjidden then show it
            $this.text("Show less");//set the text of a tag to "show less"
        } else {
            content.slideUp();// else if not hidden then hide it
            $this.text("Show more");//the the text of a tag to show more.
        }
    
    });