Dan
Dan

Reputation: 53

Is there a quicker way of writing this simple jQuery command?

I would prefer to use .slideToggle and 3 lines of code but not sure how to get the script to 'refresh' itself after it's slid open and return to it's orginal state when it's slid back up (it doesn't slide back up when I use 3 lines and a .slideToggle). Sorry for the bad technical explanation.

$('#showHide').hide();

$('a#slickShow').click(function() {
    $('#showHide').show(400);
    $('.archiveText2 a').replaceWith('<a id="slickShow" href="#">View less Blog Entries<span class="archiveLink2">{</span></a>');

$('a#slickShow').click(function() {
    $('#showHide').hide(400);
    $('.archiveText2 a').replaceWith('<a id="slickShow" href="#">View more Blog Entries<span class="archiveLink2">}</span></a>'); 

This is the code that eventually got it working

$('#showHide').hide();

$('#slickShow').click(function(){

    $('#showHide').slideToggle(400, function() {
        if ($('#showHide').is(':visible')){
          $('.archiveText2 a').html('View less Blog Entries<span class="archiveLink2">{</span>');

        }
        else{
          $('.archiveText2 a').html('View more Blog Entries<span class="archiveLink2">}</span>'); 
        }

    }); 

    return false; 
});

Upvotes: 0

Views: 127

Answers (3)

Sarfraz
Sarfraz

Reputation: 382836

As far as I could understand it, try this:

$('a#slickShow').click(function(){
  $('#showHide').slideToggle(400);

   if ($('#showHide').is(':visible')){
     $('.archiveText2 a').replaceWith('<a id="slickShow" href="#">View less Blog Entries<span class="archiveLink2">{</span></a>');
   }
   else{
     $('.archiveText2 a').replaceWith('<a id="slickShow" href="#">View more Blog Entries<span class="archiveLink2">}</span></a>'); 
   }

   return false;
});

Upvotes: 1

Andrew Wirick
Andrew Wirick

Reputation: 184

Looks like you are replacing the whole anchor when all you need to do is replace the html inside the anchor. .toggle() can be used to set up functions that work on alternate clicks. Also you can drop the 'a' from the 'a#slickShow' selector, as the ID lookup alone will be faster.

$( "#slickshow" ).toggle(
  function() {
    $(this).show(400).html( "View less Blog Entries<span class="archiveLink2">{</span>" );
  },
  function() {
    $(this).hide(400).html( "View more Blog Entries<span class="archiveLink2">}</span>" );
  });

Cheers, awirick

Upvotes: 0

trrrrrrm
trrrrrrm

Reputation: 11812

$('#showHide').hide();


$('a#slickShow').toggle(
      function(){
          $('#showHide').show(400);
          $('.archiveText2 a').replaceWith('<a id="slickShow" href="#">View less Blog Entries<span class="archiveLink2">{</span></a>');
      },
      function(){
          $('#showHide').hide(400);
          $('.archiveText2 a').replaceWith('<a id="slickShow" href="#">View more Blog Entries<span class="archiveLink2">}</span></a>'); 
      }
);

Upvotes: 0

Related Questions