Changing icons using JQuery when clicking 'show more' or 'show less' buttons

I am currently utilizing https://github.com/jasonujmaalvis/show-more to display and hide text content on a mobile device. My goal is to switch between images for show more and show less:

Here's what I have so far:

Jquery:

Source File:

;

(function($, window, document, undefined) {

    'use strict';

    var pluginName = 'toggleimages',
        defaults = {
            closedHeight: 100,
            buttonTextMore: 'show more',
            buttonTextLess: 'show less',
            buttonCssClass: 'showmore-button',
            animationSpeed: 0.5,
            openHeightOffset: 0,
            onlyWithWindowMaxWidth: 0
        };

    function Plugin(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.btn;
        this.init();
    }

    $.extend(Plugin.prototype, {
        init: function() {
            if (this.settings.onlyWithWindowMaxWidth > 0) {
                this.bindResize();
                this.responsive();                
            } else {
                this.showmore();
            }
        },
        bindResize: function() {
            var self = this;
            var resizeTimer;
            $(window).on('resize', function() {
                if (resizeTimer) {
                    clearTimeout(resizeTimer);
                }
                resizeTimer = setTimeout(function() {
                    self.responsive();
                }, 250);
            });
        },
        responsive: function() {
            if ($(window).innerWidth() <= this.settings.onlyWithWindowMaxWidth) {
                this.showmore();
            } else {
                this.remove();
            }
        },
        showmore: function() {

            if (this.btn) {
                return;
            }

            var self = this;
            var element = $(this.element);
            var settings = this.settings;

            if (settings.animationSpeed > 10) {
                settings.animationSpeed = settings.animationSpeed / 1000;
            }

            var showMoreInner = $('<div />', {
                'class': settings.buttonCssClass + '-inner more',
                text: settings.buttonTextMore
            });
            var showLessInner = $('<div />', {
                'class': settings.buttonCssClass + '-inner less',
                text: settings.buttonTextLess
            });

            element.addClass('closed').css({
                'height': settings.closedHeight,
                'overflow': 'hidden'
            });

            var resizeTimer;
            $(window).on('resize', function() {
                if (!element.hasClass('closed')) {
                    if (resizeTimer) {
                        clearTimeout(resizeTimer);
                    }
                    resizeTimer = setTimeout(function() {
                        // resizing has "stopped"
                        self.setOpenHeight(true);
                    }, 150); // this must be less than bindResize timeout!
                }
            });

            var showMoreButton = $('<div />', {
                'class': settings.buttonCssClass,
                html: showMoreInner
            });

            showMoreButton.on('click', function(event) {
                event.preventDefault();
                if (element.hasClass('closed')) {
                    self.setOpenHeight();
                    element.removeClass('closed');
                    showMoreButton.html(showLessInner);
                } else {
                    element.css({
                        'height': settings.closedHeight,
                        'transition': 'all ' + settings.animationSpeed + 's ease'
                    }).addClass('closed');
                    showMoreButton.html(showMoreInner);
                }
            });
            element.after(showMoreButton);
            this.btn = showMoreButton;
        },

        setOpenHeight: function(noAnimation) {
            $(this.element).css({
                'height': this.getOpenHeight()
            });
            if (noAnimation) {
                $(this.element).css({
                    'transition': 'none'
                });    
            } else {
                $(this.element).css({
                    'transition': 'all ' + this.settings.animationSpeed + 's ease'
                });    
            }
        },

        getOpenHeight: function() {
            $(this.element).css({'height': 'auto', 'transition': 'none'});
            var targetHeight = $(this.element).innerHeight();
            $(this.element).css({'height': this.settings.closedHeight});
            // we must call innerHeight() otherwhise there will be no css animation
            $(this.element).innerHeight();
            return targetHeight;
        },

        remove: function() {
            // var element = $(this.element);
            if ($(this.element).hasClass('closed')) {
                this.setOpenHeight();
            }
            if (this.btn) {
                this.btn.off('click').empty().remove();
                this.btn = undefined;
            }
        }
    });

    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);

My Jquery Implementation:

$('.read-more').toggleimages({
    closedHeight: 100,
    shadow: true,
    onlyWithWindowMaxWidth: 576,
    buttonCssClass: 'showmore-button',
    buttonTextLess: 'Read less',
    buttonTextMore: 'Read more'
});

CSS Styles:

.home-text .showmore-button {
    margin-bottom: 25px;
    background-image: url('../assets/images/plus-octagon-light.svg')!important;
    background-repeat: no-repeat;
    width: 150px;
    padding-left: 40px;
    height: 30px;
    display: block;
}

.home-text .showmore-button::active {
    margin-bottom: 25px;
    background-image: url('../assets/images/minus-octagon-light.svg')!important;
    background-repeat: no-repeat;
    width: 150px;
    padding-left: 40px;
    height: 30px;
    display: block;
}

.read-more { line-height:24px; }
.read-more_content { position:relative; overflow:hidden; }          
.read-more_trigger { width:100%; height:45px; line-height:45px; cursor:pointer; }
.read-more_trigger span { display:block; }

HTML Code:

<div class="home-text"><p>xxxxxxxx</p>
</div>

If anyone has any suggestions or ideas on how to toggle between icons for the show more and show less functionality while using this JS plugin, please let me know. I'm exploring where to integrate it within the plugin structure.

Answer №1

Upon further examination of the JQuery code, I found a solution that worked for me by adjusting the CSS styles for the specific classes mentioned below:

.showmore-button-inner.more {
    margin-bottom: 25px;
    background-image: url('../assets/images/plus-octagon-light.svg')!important;
    background-repeat: no-repeat;
    width: 150px;
    padding-left: 40px;
    height: 30px;
    display: block;
}

.showmore-button-inner.less {
    margin-bottom: 25px;
    background-image: url('../assets/images/minus-octagon-light.svg')!important;
    background-repeat: no-repeat;
    width: 150px;
    padding-left: 40px;
    height: 30px;
    display: block;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The three.js library encountered an ERROR 404 ( File Not Found ) when trying to import an existing file

Error: GET http://localhost:port/js/three net::ERR_ABORTED 404 (Not Found) I am currently working on a web development project using Three JS. I downloaded the master Zip of ThreeJS from the official website of Three JS I copied the JS files from the Bui ...

Choose a row in an Angular ngGrid upon loading the page

My question is in relation to this inquiry How can I retrieve selected rows from ng-grid? Check out the plunker sample - http://plnkr.co/edit/DiDitL?p=preview Upon page load, I am looking to have a row pre-selected without relying on 'ngGridEventDa ...

Incorrect pathing in express.js

I've encountered an issue with my filter while attempting to redirect packages using two express.js routes: app.get('/billdetails/:year/:month/:phoneId', function (req, res, next) { var db = req.db; var year = req.params.year; v ...

Assign value to twig variable using JavaScript in Symfony version 3.4

Hello everyone, I am currently working on a form that is functioning well. However, I am facing an issue with setting the localization of a place manually using latitude and longitude values. To address this, I decided to create a map with a draggable mark ...

Ways to retrieve the React Router match object in mapStateToProps

Is there a way to access the react-router match object for its params from mapStateToProps or any other selector? I'd like to use these params to generate a value that will be passed down as props to a presentational component within the selector. The ...

I have been attempting to implement validation in JQuery, but it doesn't seem to be functioning correctly

Can someone assist me with adding validation in jQuery? I'm stuck and need help solving this problem. $(function(){ $("#btn").click(function(){ var b=prompt("Enter your link"); $("a").attr("href",b); if($("b").v ...

Clones are made sortable instead of arranging them in a specific order

I have a list that can be sorted with some customizations. However, I am facing an issue where the items in the list get duplicated every time I try to sort them. When I pull one item to sort it, another copy gets added automatically. I am struggling to u ...

The AngularJS beginner routing application is malfunctioning and needs fixing

I've been diving into Angular JS but hit a roadblock with a basic angular routing program. I need some guidance on what's going wrong. If you want to check out the complete project code, visit my GitHub repository: https://github.com/ashpratap00 ...

What kind of influence will JQuery have on the world of Web design and

With the rising popularity of JQuery in the tech world, it's no surprise that there are currently 8,470 questions tagged with JQuery on Stack Overflow. As the 10th most popular topic on the site, it's clear that JQuery is a force to be reckoned w ...

HTML5 coding can be enhanced by applying unique CSS rules for alignment purposes

html { font-family: "Open Sans", sans-serif; font-weight: 100; background-color: #fbfbfb; } body { font-family: "Open Sans", sans-serif; font-weight: 100; } body h1 { font-weight: 100; } body h3 { font-family: "Open Sans", sans-serif; fo ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

the jquery script failed to execute

After placing a repeater inside an update panel and adding a jQuery function to add effects, I encountered an issue. The jQuery function, which is called on every page load event, works perfectly on a test page but does not show any effects when implemente ...

"Creating a cascading dropdown in ASP.NET MVC: Making one dropdownlist dependent

This part of the platform is dedicated to creating job listings. Users are required to select an Area and Subarea when creating a job offer. Upon selecting an Area, relevant Subareas should be displayed. To get a visual representation of the table structur ...

Slider with FadeIn effect remains unresponsive to the FadeOut command (JQuery / Javascript)

I'm currently working on a slider that is supposed to fade in and out. However, I am facing an issue where the slide fades in correctly but instantly disappears instead of fading out. Do you have any insights into why this might be happening and any s ...

Tips for creating a navigation system that combines both horizontal and vertical bars

Is there a way for me to have both horizontal and vertical navigation bars on my website? I am new to design and struggling to understand why my CSS isn't working properly when applied to multiple links. <body> <div class="horizontallinks" ...

Utilizing data attributes and JavaScript to dynamically assign a class to carousel navigation items

Hello there! I recently created a carousel and carousel navigation system using Bootstrap. I am now trying to figure out how to detect the value of 'data-slide-to' and then apply a specific style to the corresponding navigation item based on that ...

Boss declares, "Display the iFrame with no borders visible."

Good day to everyone, I am currently dealing with an issue on the page: It seems to be working perfectly in all of my browsers except for Internet Explorer. Since I don't have IE, I'm having trouble troubleshooting this. My boss mentioned somet ...

The JQuery code is failing to remove the dynamically added field when the delete icon is clicked

Information: I am currently navigating the world of programming and attempting to build a To-Do List feature. When the create list button is clicked, a dynamically generated div with the class 'wrap' is created. This div contains two nested divs: ...

I am looking to transform my string code into a PDF file using an ASP.NET MVC controller by passing the string through an AJAX call to the controller

Currently, I am attempting to change an HTML string into a PDF format using iron PDF within the asp.net-mvc environment. However, since it is only a trial version, could you provide me with an alternative solution to converting an HTML string to a PDF in ...

troubles with dividing string

Recently delving into JavaScript/Angular development and encountering a little roadblock. I am attempting to break up a string of a textarea into an array at the \n character within a controller by utilizing $scope.mytext.split("\n"), however, I ...