How to fire on click function fire only one time?

How to fire on click function fire only one time?
0

http://jsfiddle.net/btmg3u6f/

I mean when click on one or two that only first time scroll that id? In second click do nothing?

Thanks.

Just use a function called “off.” Please see below.

$("a[href^='#']").click(function scroll(e) {
  e.preventDefault();

  var position = $($(this).attr("href")).offset().top;

  $("body, html").animate({
    scrollTop: position
  } /* speed */ );
  $(this).off('click')
});
1 Like

Thanks for answer!

I try it http://jsfiddle.net/L2yqw4ha/ but not seems work I mean when click on it agan and again do the event.

http://jsfiddle.net/h83gjqse/

Vanilla javascript. Problem solved.

1 Like

You have to choose the last version of jQuery.

http://jsfiddle.net/pwbr08ef/

Is it fine now still my question how can do that like above vanilla JS example to do nothing about click? I mean when click on it do nothing? Because is not do animate but still does to jump to id.

Thanks!

jquery solution:

http://jsfiddle.net/h83gjqse/1/

1 Like

There

$("a[href^='#']").click(function(e) {
  e.preventDefault();

  var position = $($(this).attr("href")).offset().top;

  $("body, html").animate({
    scrollTop: position
  } /* speed */ );
  $(this).off('click');
  $(this).click(function(e) {e.preventDefault()} )
});

1 Like

@Michael_J you’re missing his issue.

He only wants links to work one time. Look at my solution.

Here is a slightly different way to do it with jQuery:
http://jsfiddle.net/L2yqw4ha/

1 Like

You’re missing his request too. He wants the links to only click once. Notice how in your example if I scroll back to top and click “One” is scrolls again. Look at my solution.

1 Like

@kerafyrm02 My links only work one time.

Yes you are right only one time and yes is about .one function. Thank you!

@RandellDawson

Nope,. it works multiple times. Unless you linked us wrong one.

I thought I had clicked save. Try this one.

http://jsfiddle.net/1ykdh28p/

Why do you think it is better than your use of the one method?

1 Like

Ya-- works. And your solution I would argue is even better than mine.

1 Like

Ahah now whitch the best one to accept :smiley: ?

If he wanted other functionalities to occur with those links the .one() approach is the way to go,. but strictly answering his question,. your approach is better.

Because your approach only adds one eventlistener.

1 Like