Currently reading a jQuery tutorial from the Head First series and practicing with an example where I need to identify the last selected element.
In Chapter 2, there is a task involving four images on a page. When a user clicks on any of these images, they receive a random discount message that appears below the image. To make it more visually appealing, I incorporated the slideUp()
function which was introduced in Chapter 1 of the same book.
So far, when a user clicks on an image, the discount message slides down beneath it revealing the offer. If another image is clicked, the previous message slides back up and a new one displays below the newly selected image. Below is a simplified version of my code.
$('.jumpDiv').click(function () {
$('.jumpDiv').children('.discountDiv').slideUp();
$('.jumpDiv p').remove();
var discount = Math.floor((Math.random() * 5) + 5);
var msg = '<p>Your discount is ' + discount + '%</p>';
$(this).children('.discountDiv').append(msg);
$(this).children('.discountDiv').slideDown();
});
.jumpDiv{
float:left;
}
#main{
border:1px solid;
height:500px;
width:auto;
background-color: grey;
}
#main .jumpDiv{
border-right: 1px solid;
border-bottom: 1px solid;
height:245px;
width:245px;
font-size:20px;
}
#main .jumpDiv>div{
text-align:center;
background-color:#fee;
cursor: pointer;
}
.discountDiv{
text-align: center;
display:none;
border:1px solid;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<body>
<div id="main">
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
</body>
The issue I'm facing revolves around preventing the discount message div from sliding up and down multiple times if the same image is repeatedly clicked. Is there a way to detect the last clicked element and modify the behavior such that the message updates without unnecessary animations?