user3366010
user3366010

Reputation: 17

jQuery open and close on click

I am trying to use the click function to expand an element, alter the elements html, and the on click again minimize the element

I wrote this jQuery code

$(".servicereadmore").click(function () {
    $('.myinfo').css("height", "100%");
    $(this).html("Read less");
    $(this).removeClass("servicereadmore");
    $(this).addClass("servicereadless");
});
$(".servicereadless").click(function () {
    $('.myinfo').css("height", "200px");
    $(this).html("Read more");
    $(this).removeClass("servicereadless");
    $(this).addClass("servicereadmore");
});

servicereadmore and servicereadless are the class of the anchor tag.

The 1st click fires fine, the myinfo div expands and the anchor tag text and class change, however the second click function won't fire

Upvotes: 0

Views: 88

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use on() for dynamically added classes like

$(document).on('click',".servicereadmore",function () {
    $('.myinfo').css("height", "100%");
    $(this).html("Read less")
           .toggleClass("servicereadmore servicereadless"); // use toggleClass
});
$(document).on('click',".servicereadless",function () {
    $('.myinfo').css("height", "200px");
    $(this).html("Read more")
           .toggleClass("servicereadmore servicereadless"); // use toggleClass
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need event delegation. Use .on() instead:

            $(document).on('click',".servicereadmore",function() {
                $('.myinfo').css("height" , "100%");
                $(this).html("Read less");
                $(this).removeClass("servicereadmore");
                $(this).addClass("servicereadless");
                });

            $(document).on('click', ".servicereadless" ,function() {
                 $('.myinfo').css("height" , "200px");
                 $(this).html("Read more");
                 $(this).removeClass("servicereadless");
                 $(this).addClass("servicereadmore");
            });

Upvotes: 1

Related Questions