I'm learning jQuery and get stuck in a problem of selector.
I've got a function that hide and show element but I'm trying to apply it precisely to the element click instead of to all the element.
I tried with $(this) but I guess I was not specific enough.
Here is the jsFiddle
And this is the function
$(document).ready(function(){
if($('.resume').text().length > 100)
{
complet = $('.resume').text();
complet += '<span class="showLess"> Cacher</span>';
html = $('.resume').text().slice(0,100);
html += '<span class="showMore">...</span>';
$('.resume').html(html);
}
$(document).on('click','.showMore', function(){
$('.resume').html(complet);
showLess();
});
function showLess(){
$('.showLess').on('click', function() {
$('.resume').html(html);
});
}
});
If someone can indicate me where shall I head ? closest ?
There are multiple problems here....
So
/* Maël check : Marche presque */
jQuery(function () {
$('.resume').each(function () {
var text = $(this).text();
if (text.length > 100) {
var less = text.slice(0, 100) + '<span class="showMore">...</span>';
$(this).html(less);
$(this).data('content', text + '<span class="showLess"> Cacher</span>')
$(this).data('less', less)
}
});
$(document).on('click', '.showMore', function () {
var $res= $(this).closest('.resume');
$res.html($res.data('content'));
});
$(document).on('click', '.showLess', function () {
var $res= $(this).closest('.resume');
$res.html($res.data('less'));
});
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-xs-4">
<div class="resume">Bonjour je suis un gros Chat. Bonjour je suis un gros Chat. Bonjour je suis un gros Chat Bonjour je suis un gros Chat Bonjour je suis un gros Chat Bonjour je suis un gros Chat Bonjour je suis un gros Chat Bonjour je suis un gros Chat</div>
</div>
<div class="col-xs-4">
<div class="resume">Cette fois ci un poisson ! Cette fois ci un poisson ! Cette fois ci un poisson ! Cette fois ci un poisson ! Cette fois ci un poisson !</div>
</div>
I would have done it like this:
$('.resume').each(function() {
var resume = $(this),
text = resume.text();
if (text.length > 100) {
var showLess = '<span class="showLess"> Cacher</span>',
showMore = '<span class="showMore">...</span>',
sliced = text.slice(0, 100);
resume.html(sliced + showMore);
resume.on('click', '.showLess', function() {
resume.html(sliced + showMore);
});
resume.on('click', '.showMore', function() {
resume.html(text + showLess);
});
}
});
Updated fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With