Reputation: 511
How can I modify this script so that I can add any text in the button. I just want to append the + or - sign instead of all the text.
JAVASCRIPT
$(document).ready(function(){
function changeText(text) {
return (text.indexOf('+') >= 0) ? 'Shop Now -' : 'Shop Now +';
}
$(".dropbtn").click(function() {
var $this = $(this), $dropdownActive = $('.dropdown-active');
/* changing the text of the active button (if any) */
$dropdownActive.text(changeText($dropdownActive.text()));
/* hiding the content under the active button (if any) */
$('.dropdown-content', $dropdownActive.parent()).slideToggle('show');
if (!$this.hasClass('dropdown-active')) {
/* changing the text of the clicked button */
$this.text(changeText($this.text()));
/* showing the content under the clicked button */
$('.dropdown-content', $this.parent()).slideToggle('show');
/* adding this class to the clicked button */
$this.addClass('dropdown-active');
}
/* removing this class from the active button */
$dropdownActive.removeClass('dropdown-active');
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var $dropdownActive = $('.dropdown-active');
/* changing the text of the active button (if any) */
$dropdownActive.text(changeText($dropdownActive.text()));
/* hiding the content under the active button (if any) */
$('.dropdown-content', $dropdownActive.parent()).slideToggle('show');
/* removing this class from the active button */
$dropdownActive.removeClass('dropdown-active');
}
}
thanks!!!
https://jsfiddle.net/jf1zetLw/11/
Upvotes: 0
Views: 192
Reputation: 31692
You should check if there is a +
sign to replace it with a -
or if there is a -
to replace it with +
like this:
function changeText(text) {
if(text.indexOf('+') >= 0) // if we have a +
return text.replace('+', '-'); // return the text after replacing + with -
return text.replace('-', '+'); // otherwise return - replaced with +
}
Or a shorthand like yours:
function changeText(text) {
return (text.indexOf('+') >= 0) ? text.replace('+', '-'): text.replace('-', '+');
}
Upvotes: 1