Attempting to implement CSS onto jQuery slideToggle upon the clicking of links

Need to implement a show/hide functionality for a series of lists using jQuery slideToggle. After clicking on the hyperlinks that trigger the show/hide action, I want to change the CSS style of those hyperlinks and then revert back to the original style upon clicking them again. I found inspiration from this example:

Here's a snippet of the code:

$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);

The following code worked for me:

$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText).css({ backgroundColor: '#399C05' }) : toggleClick.text(options.showText).css({ backgroundColor: '#FFFFFF' });

However, I need to change the background image in the CSS instead of just the background color:

$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText).css({ background: url(/images/icon_image1.gif) }) : toggleClick.text(options.showText).css({ url(/images/icon_image1.gif) });

Trying this resulted in an error "Microsoft JScript runtime error: Object doesn’t support this property or method" and caused the show/hide functionality to stop working.

I also attempted to switch classes on click with:

$('#toggleDiv').toggleClass('show_hideClose', $(this).is(':visible'));

Specifying show_hideClose as a duplicate of show_hide led to the same error mentioned above.

Code snippet:

$('.show_hide').showHide({
    speed: 1000,    
    easing: '',    
    changeText: 1, 
    showText: 'View Available Programs', 
    hideText: 'Hide Program Listing' 
});

and

(function ($) {
    $.fn.showHide = function (options) {

        var defaults = {
            speed: 1000,
            easing: '',
            changeText: 0,
            showText: 'Show',
            hideText: 'Hide'

        };
        var options = $.extend(defaults, options);

        $(this).click(function () { 

            $('.toggleDiv').slideUp(options.speed, options.easing); 

            var toggleClick = $(this);
            var toggleDiv = $(this).attr('rel');

            $(toggleDiv).slideToggle(options.speed, options.easing, function() {
                if(options.changeText==1) {
                    $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
                }
            });

            return false;      
        });
    };
})(jQuery);

The hyperlink is located within a .NET C# repeater:

<asp:Repeater ID="rptMyContentGroups" runat="server" OnItemDataBound="rptMyContentGroups_OnItemDataBound">
    <ItemTemplate>            
    <a href="#" id="blah" class="show_hide" rel='#                                                <%=rptmyContent.ClientID%>_programList_<%# GetDivClass() %>'>View</a>
        <div id="programList" runat="server" style="display: none;">
        <asp:Repeater ID="rptMyContent" runat="server" OnItemDataBound="rptMyContent_OnItemDataBound">
            <HeaderTemplate>    
                <ul>
            </HeaderTemplate>
            <ItemTemplate>
                <li>
                    <asp:HyperLink ID="hypContentDetail" runat="server" />
                </li>
            </ItemTemplate>
            <FooterTemplate>
                </ul>    
            </FooterTemplate>
        </asp:Repeater>
        </div>
    </ItemTemplate>
</asp:Repeater>

UPDATE:

Attempted the following code:

$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText).css('background-image', 'url("' + /images/icon_a.gif + '")') : toggleClick.text(options.showText).css('background-image', 'url("' + /images/icon_b.gif + '")');

Received an error in IE about missing parentheses, which is not the case. Visual Studio displayed: "Microsoft JScript runtime error: Object doesn't support this property or method".

Answer №1

If you are looking to modify the background-image css property, you can follow this syntax:

$(toggleDiv).is(":visible")
    ? toggleClick
        .text(options.hideText)
        .css('background-image', 'url(/images/icon_image1.gif)')
    : ...


However, a better approach would be to enhance your plugin by incorporating an option and utilizing addClass/removeClass. By doing so, you can make your plugin more adaptable without embedding the image URL into the code.

// include the option
$('.show_hide').showHide({
    ...
    showText: 'View Available Programs',
    hideText: 'Hide Program Listing',
    hideClass: 'myClassForHide'
});

// implement it in your toggle
$(toggleDiv).is(":visible")
    ? toggleClick
        .text(options.hideText)
        .addClass(options.hideClass)
    : toggleClick
        .text(options.hideText)
        .removeClass(options.hideClass)

Answer №2

Well, it appears that the key to success lies in the syntax and quotes used. Check out how this code snippet solved the problem:

$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText).css('background-image', 'url(/images/image1.gif)') : toggleClick.text(options.showText).css('background-image', 'url(/images/image2.gif)');

I can't believe I didn't think of trying that sooner.

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

Is there a way to access just the concealed text within an element?

Is there a way to create a JavaScript function that can specifically extract hidden text from an element? Are there any existing libraries with this capability, and if so, how efficient are they? In order for an element to be considered visible ac ...

What is the best way to incorporate one Div within another Div using JavaScript?

I have a single main div with an id, and I am looking to insert 4 additional child divs inside it. Each of these child divs will then contain 5 more divs each. The code snippet that I currently have is as follows: $( document ).ready(function() { for( ...

Is it possible to use velocity js to add a gradient color effect to text content?

Can I use velocity js to apply gradient color to text? I've looked at https://css-tricks.com/snippets/css/gradient-text/ My specific need is to dynamically add a changing gradient using js. Thank you in advance. ...

Expansive space for floating numerous tiny circles in the air

Presently, I have a map that features several small circles/dots created using the border-radius property. When hovering over a dot, it triggers an animation along with other effects. MY CONCERN: At the moment, I need to be incredibly accurate when tryi ...

Traversing tables with JQuery's nextUntil function

I have a calendar table where I need to highlight the range from the pickup date, maybe 10 Feb, to the set date of 20 Feb. <tr class="rd-days-row"> <td class="rd-day-body rd-day-disabled">09</td> <td class="rd-day-body">10& ...

Managing content in two separate divs at the same time using AJAX

I am curious to know how I can achieve a functionality where editing the text field on the left will automatically update the text field on the right. I have a feeling that it involves using AJAX, and I would like to implement it as well. Can anyone guid ...

JSON to Table Conversion

On the hunt for a php script that can load CSV files? Look no further than this snippet: echo json_encode(file(csvfile.csv, FILE_IGNORE_NEW_LINES)); Check out the output: ["foo,bar,baz","foo, foo,bar","bla,bla,blubb"] Need to integrate this into your ...

Can a key event be activated on the DOM Window using Javascript or JQuery?

Can a key event be triggered on the DOMWindow or DOMDocument using JavaScript? I am developing a browser extension to interact with a website that has shortcut key events, similar to those in GMail. While I have come across other methods for triggering key ...

Breaking down ZipFile into numerous smaller fragments and then reassembling those fragments to reconstruct the original ZipFile

I am facing an issue while trying to transfer a large zip file to a remote server. In order to overcome this problem, I have attempted to split the zip file into smaller chunks and send these individual pieces to the remote server. However, upon combining ...

Interacting with XML using jQuery, (XML not valid)

I am experiencing a challenge with extracting data from what seems to be an XML file using jQuery: Below is the jQuery code I have been using, which works perfectly with a standard XML file: $.ajax({ type: "GET", url: "test.xml", d ...

Problems with CSS animations on mobile devices in WordPress

On my website powered by Elementor Pro, I have implemented custom CSS to animate the Shape Divider with a "Brush Wave" style. Below is the code snippet: .elementor-shape-bottom .elementor-shape-top .elementor-shape body { overflow-x:hidden; } @keyframes ...

fa-arrow-circle-o-down and fa-arrow-circle-down

Is it possible to modify the fa-arrow-circle-o-down icon to have the same arrow type as the fa-arrow-circle-down icon? The current arrows on these two icons are different and I want them to be consistent. ...

Is it possible to superimpose a post-type title onto the featured image?

I have crafted this WP_Query to extract the titles and featured images from my post types. <div class="job-cont"> <?php $query = new WP_Query( array( 'post_type' => 'jobs' ) ); if ( $query->have_posts( ...

What is the best way to send JSON data to a code behind method instead of a Webmethod?

I have a dilemma with handling JSON data in my code behind to bind it to an obout grid. While I am aware of passing data using the <WebMethod>, I've encountered limitations as the method is static, making it difficult to bind the data to any gri ...

Executing a series of functions sequentially in jQuery

I have a pair of function groups: $(document).ready(function() { var id = $(this).attr('id'); // The first group of functions getCountry(id); // The second group of functions getResult(id, 'all'); }); Eac ...

Is it possible to leverage AngularJS string interpolation ({{}}) within the jQuery HTML function?

I am attempting to implement angularJs string interpolation within the Jquery html function $('#existingScoresForWeek').html("<p>{{1 + 1}}</p>"); Unfortunately, the code above is not displaying the Result as 2 <div data-ng-app=" ...

Decrease the size of ion-list items in Ionic 2

I found a similar query over on Stack Overflow, but it's related to Ionic 1 where the ion-item still includes ion-content. In Ionic 2, there is no ionic-content element. I've attempted to adjust the height, padding, and margin of both the ion-ite ...

Step by step guide to applying a personalized "margin" to your CSS

I have set the body element's margin to 0 in my CSS stylesheet. However, I am struggling to successfully set the margin for the div elements. Therefore, I would like to set all other things' margin to 0; except for the div elements with the cl ...

Guide on Creating a cssSelector for the Advanced jQuery Selector Demonstrated

Looking for help with converting a jQuery selector to a cssSelector in Selenium. Here is the jQuery selector I have: jQuery("iframe#msg_body").contents().find("html body div span").text() I need to use this as a cssSelector in Selenium, similar to the fo ...

Adjust the DIV shape to fit perfectly within the browser window without overlapping with any other elements

http://jsbin.com/iGIToRuV/1/edit Currently, I am working on developing a WYSIWYG website designer as part of an experimental project for various purposes. The ultimate goal is to ensure that it is both desktop and mobile-friendly. However, I have encount ...