user3784158
user3784158

Reputation: 1

append once with javascript href link

I know it has been posted before on how to append only once, but my situation is a little unique because I'm attempting to call the function from an href link. I have my code posted on jsfiddle, but it's not working for some reason. The same code on my site works. Can someone help me get this working so that clicking the href link will append a given string to the #services div only one time. The code thats on my actual site appends the "details" over and over again every time I click the link, but I only want it to do it once.

<div id="services">SERVICES</div>
<a href="javascript:moreDetails();">More Details</a>
var details = '<p>Just some additional details</p>';
function moreDetails(){
        $('#services').append(details);
}

http://jsfiddle.net/7g59yb5r/1/

Upvotes: 0

Views: 894

Answers (3)

Morrisda
Morrisda

Reputation: 1420

Simply do:

<div id="services">SERVICES</div>
<a href="javascript:moreDetails(this);">More Details</a>
var details = '<p>Just some additional details</p>';
function moreDetails(obj){
        obj.setAttribute("href", "")
        $('#services').append(details);
}

Upvotes: 0

gkunz
gkunz

Reputation: 1423

I'd strongly recommend you to follow a data attribute based approach for adding such kind of behavior. Otherwise you'll end up with a huge pile of spaghetti code. I recently prepared a small presentation about what I like to call data driven behavior.

Assuming that for your case it would also be fine to show / hide the details with a toggle button you could add such re-usable behavior with a few simple lines of code:

  $('[data-toggle-show]').each(function() {
    var $element = $(this),
        $target = $($element.data('toggleShow'));

    $target.hide();

    $element.on('click', function() {
      $target.toggle();
    });
  });

Then you can use this functionality anywhere in your markup using a data attribute:

<p>Welcome to the article. Do you want to read more?</p>
<button data-toggle-show="#article-more">read more</button>
<p id="article-more">Here you go! Some more to read...</p>

You can view the example on jsbin

Also, in my opinion, the correct HTML semantics for such behavior is to use a button instead of a link. I've also used a link in the past until I read an interesting debate on where to use a link and where to use a button. Actually the bottom line is that a link should be used where a user can right click to bookmark the URL and a button should be used where you could also decide to disable the possibility to execute the behavior.

Upvotes: 0

j08691
j08691

Reputation: 208040

I'd use .one() and do it like:

var details = '<p>Just some additional details</p>';
$('a').one('click',function () {
    $('#services').append(details);
})

jsFiddle example

Upvotes: 1

Related Questions