Reputation: 63
So after trying to get something to work I came up with this code (which allows for a more / less button that will stay open or closed whenever the page will be refreshed:
var isCompactListOpen = localStorage.getItem('isCompactListOpen') || false;
function setButtonText() {
if (isCompactListOpen) {
$(this).text('Show less');
} else {
$(this).text('Show more');
}
}
if ($('.ty-compact-list').length > 3) {
setButtonText();
$('.show-more').show();
if (!isCompactListOpen) {
$('.ty-compact-list:gt(2)').hide();
}
}
$('.show-more').on('click', function() {
//toggle elements with class .ty-compact-list that their index is bigger than 2
$('.ty-compact-list:gt(2)').toggle();
//change text of show more element just for demonstration purposes to this demo
isCompactListOpen = !isCompactListOpen;
localStorage.setItem('isCompactListOpen', isCompactListOpen);
setButtonText();
});
But now it gives me this error in the google chrome web console:
jquery.min.js:4 Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
at dt (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:23993)
at Function.buildFragment (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:31426)
at init.domManip (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:28300)
at init.append (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:26162)
at init.$.fn.(anonymous function) [as append] (http://dev.***.com/var/cache/misc/assets/js/tygh/scripts-4e16721e1fc39760420d82fb157574bd1483617255.js:681:688)
at init.<anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:25287)
at Function.access (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:6600)
at init.text (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:25224)
at setButtonText (http://dev.****.com/****/:4641:13)
at http://dev.****.com/****/:4646:3
Any help would be appreciated!
Upvotes: 2
Views: 2441
Reputation: 600
I think the issue may because you are using this instead of a selector. The this context is wrong in the setButtonText function.
Try this:
function setButtonText() {
if (isCompactListOpen) {
$('.show-more').text('Show less');
} else {
$('.show-more').text('Show more');
}
}
Upvotes: 3