jQuery Event Handler – Effect of Return Statement

Today, I need to discuss the effect of return false usage in an event handler if you are using jQuery.

I am providing a simple HTML content to check this out in real time. Here is our HTML content.

<!DOCTYPE html>
<html lang="">

<body>

    <div class="link-holder" id="link-holder">
        <a class="my-link" id="my-link" href="index.php">I am link</a>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>

</html>

Nothing fancy here. Our html page contains a simple attribute tag enclosed by a div container. We added jQuery from Google CDN and also a custom script file js/script.js.

Default Working of Event Handlers

Our scipt.js file looks like this:

$(function ($) {
var $a = $('.my-link');
var $div = $('.link-holder');

$a.on('click', function () {
$(this).text('Hi From First');
});

$a.on('click', function () {
$(this).text('Hi From Second');
});

$div.on('click', function () {
$a.text('Hi From Third');
});
});

As you can see it registers three click event handlers. Two of them for attribute tag and one for the container div tag.

When we execute and click on the attribute link, what would you think of the result? If you are thinking it would be Hi From Third, you are wrong. The page will get reloaded and the text would be again I am link.

The reason for this is simple. Even though it registers three event handlers for the click event, none of it stopping the default behaviour of attribute tag. So after executing all the event handlers, it will go on with its default behaviour which is loading the href page mentioned.

The Effect: Stopping Default Behaviour

If you want to stop this, you can add event.preventDefault() in any of the event handlers. This will stop the default behaviour attribute tag. To demonstrate this, we are changing the second event handler to below:

$a.on('click', function (event) {
event.preventDefault();
$(this).text('Hi From Second');
});

Now if you reload the page and click on the attribute tag, then you will see below result

As you can attribute tag default behavior is no more working and it shows the last executed event handlers output.

Now we are doing changing the code like this below:

$(function ($) {
var $a = $('.my-link');
var $div = $('.link-holder');

$a.on('click', function () {
$(this).text('Hi From First');
});

$a.on('click', function () {
$(this).text('Hi From Second');
});

$div.on('click', function () {
$a.text('Hi From Third');
return false;
});
});

Here the only difference is, we are adding return false in the 3rd event handler. Now if you reload the page and click on the attribute tag, you will see the same output as you see above.

That’s cool. We now understood adding a return false prevents the default behaviour, just like event.preventDefault() does.

The effect: Stopping Event Propagation

Now let us put the same return false statement in the second event handler as you can see below:

$(function ($) {
    var $a = $('.my-link');
    var $div = $('.link-holder');

    $a.on('click', function () {
        $(this).text('Hi From First');
    });

    $a.on('click', function () {
        $(this).text('Hi From Second');
        return false;
    });

    $div.on('click', function () {
        $a.text('Hi From Third');
    });
});

The result is shown below:

Ah.. that’s interesting. It looks like the third event handler didn’t execute at all. so return false stopping next event handlers from execution? It looks like so. But wait, Let us add the return false in the first event handler in order to make sure it.

$(function ($) {
var $a = $('.my-link');
var $div = $('.link-holder');

$a.on('click', function () {
$(this).text('Hi From First');
return false;
});

$a.on('click', function () {
$(this).text('Hi From Second');
});

$div.on('click', function () {
$a.text('Hi From Third');
});
});

If you check the output now, you will see Hi From Second. Exactly what you see above!!. This mean it executes all event handlers that are bind on attribute tag, but not the event handler that bind on the container div.

Whenever an event is fired on the element, the browser will fire the same event for all of its parent elements. This is known as event propagation. So here return false stops the event propagation. But, it will keep on executing event handlers bind on the same element though!!!

Effect of return; or return true

If you try other return formats such as return; or return true, you will observe that there is no effect for them. For example, if you add any one of it in the first event handler and try out, you will see that page will reload again (default behaviour of attribute tag).

Is there any effect in pure javascript if use return false

There are no such “side effects” if we use pure javascript for it. For example , the below code:

$(function () {
var a = document.getElementById('my-link');
var div = document.getElementById('link-holder');

a.addEventListener('click', function (event) {
event.target.innerText = 'Hello From First';
return false;
});

a.addEventListener('click', function (event) {
event.target.innerText = 'Hello From Second';
});

div.addEventListener('click', function () {
a.innerText = 'Hello from Third';
});
});

You will see the output as the page reload again. So there is no effect for return false in pure javascript.

Related: lloyds pharmacy newham hospital opening times, rebecca john lawyer husband, are there chiggers in south dakota, las vegas residency october 2023, darren mcgavin children, ronnie o’neal daughter autopsy, demons in european folklore, asbury park, nj shooting, houses for rent by owner in macon, ga, longest mlb game in last 10 years, brady funeral home coxsackie, joe montana high school stats, your item departed a transfer airport the item is currently in transit to the destination, f150 coolant leak passenger side, orbital notation for calcium,Related: spencerport high school staff, my cat ate a shamrock plant, esplanade gardens harlem for sale, joselo vega menudo, 1974 gopher football roster, santa clara university basketball camp 2022, marc cohen obituary, natasha fyles parents, 250 gallon preformed pond, average time off work with sciatica, firestone legends day concert 2022, bandon dunes secret stash, laura moretti tom berenger, yancey county arrests 2021, how much does a football stadium make per game,Related: striploin vs ribeye calories, difference between current relay and potential relay, crime times luray, va, why do my fingertips smell like garlic, lum’s restaurant locations, 23 people died at michael jackson concert, , mimi rogers and tom cruise wedding photos, wedding venues in fort worth under $3,000, fort hood garrison commander, trey gowdy new show ratings, matt ranaudo age, 7 days to die darkness falls coal, eon smart meter vend mode, st george catholic church mass schedule,Related: how much does a bushel of shelled peas cost, shinra kusakabe devil form, is jimmy houston’s wife chris still alive, i’m nobody who are you worksheet, columbia county shooting, chris cuomo podcast ‘the handoff, bumgarner funeral home troy, nc obituaries, vampire attacks in new orleans 2022, shred 2 tweak a trick, the red record sparknotes, kz1000 vance and hines exhaust, cook partisan voting index by district, who has passed away from hee haw, how long does mariner finance take to approve, forsyth county, nc magistrate,Related: firefighter residency programs washington, vrbo wedding venues san diego, houses for rent in danville, va, reading to liverpool street crossrail journey time, 2004 russia farmacon bromomethane explosion, jennifer lopez skin tone, waukesha ymca pool schedule, pastor david rosales net worth, tessa thompson married to janelle monae, field specialist rivian salary, richard mcmillan texas, elizabeth mitchell husband, psychiatric hospital sacramento, what happened to jason bose smith, camillagate transcript full,Related: anglo saxon female features, black personal trainers san diego, jefferson county tn burn permit, golf tournaments in nc 2022, quickest route to santa fe new mexico, dodd rehabilitation hospital, how to remove stains from silicone spatula, deseret news obituaries, covid crimes against humanity del bigtree, university blue color code, nurse murdered in leamington spa, tornado warning charlotte nc now, eastern shore undercover now, what years are the fia and cma from, ano ang pamamaraan sa paglalaro ng agawan base,Related: mt lebanon football coaching staff, gillick competence osce, boyfriend doesn’t invite me to family events, bd veritor covid test results without app, cheiro predictions about hinduism, residential construction cost per square foot by zip code, studio 60 miami shooting, how much does the 8g band get paid, israeli owned companies in the us, best and worst moon signs, american express digital marketing strategy, distance decay of pizza, ivation wine cooler troubleshooting, thomas gibson daughter, classic cars of sarasota inventory,Related: country radio stations victoria, koolysmiley boyfriend, how to grow creeping fig on steps, redondo beach school district permit, hatch horror game ending explained, wake forest women’s soccer id camp 2022, berthoud rec center membership, souls saga script, smart appliances examples, can i return morphe products at ulta, mission bbq black lives matter, qatar airways heathrow terminal 5 arrivals, economic importance of peepal tree, islington council commercial property, importance of multimedia in entertainment,Related: girl names that end in yn, john melendez tonight show salary, el producto cigars out of business, tornado catamaran for sale, 55th grand boule, nahradne diely na vzduchovku kandar, nc hope program reopening, 290 broadway immigration court, para que sirven los cuernos de la vaca, friday health plans timely filing limit, vodafone tracker fob battery replacement, pabst blue ribbon hard coffee expiration date, catalina helicopter crash, kwlm radio obituaries, board and train for aggressive dogs,Related: why did david baker leave forged in fire, wisconsin state high school track records, aimlabs rank distribution, northwest patriots motorcycle club, le musicien le plus riche du congo kinshasa, wreck in mt sterling, ky today, jim smith top chef gender, banksia roots invasive, brown sugar cure recipe, aau basketball tournaments in georgia 2022, deped pledge of commitment for teachers, gyn onc fellowship rankings, hawaiian airlines airbus a321 best seats, khalil mack double team percentage 2021, michael louding family killed,Related: linda raschke strategy, st louis symphony at forest park 2022, condos near dog days lake of the ozarks, isburg funeral home pierre, can i cross cbx with birth certificate, chase bank death of account holder, caughman harman funeral home lexington, sc obituaries, duke volleyball: roster, hijos de helena rojo y juan ferrara, alexander rossi family, why did brittney payton leave fox news, jake harris deadliest catch wife, carl muldoon actor, eunice garrett, wife of bernard garrett, can dracthyr stay in human form,

Rajeev K Tomy

4,919 thoughts on “jQuery Event Handler – Effect of Return Statement

  1. Pingback: 2adroitly
  2. Pingback: costco cialis 5 mg
  3. I thank you very much rabbi Miriam Jerris!Your article, so frankly, reflects exactly what I am experiencing in my marriage daily.I am married with a socialist who professes the Protestant religion, where circumcision is not a common practice. Even so, he did it as a sign of love and respect for my Jewish background.We believe that with our political differences, we have managed to live relatively in harmony in this very rural environment that is this Spanish Galicia.We are both a gay couple from Denmark, married (in Copenhagen) since 2007.Happy New Year!Alex Schmidt

  4. i / hello there
    i have learn several just right stuff here. Definitely value bookmarking for revisiting I just would like to give you a huge thumbs up for the great info you have right here on this post.“밤의전쟁” m really impressed with your writing skills and Aspectmontage makes it easy as can be and affordable for you to upgrade your windows, doors, roofing, showers or baths.

  5. I have read your article carefully and I agree with you very much. This has provided a great help for my thesis writing, and I will seriously improve it. However, I don’t know much about a certain place. Can you help me?

  6. hello!,I really like your writing very a lot!
    percentage we be in contact more about your article on AOL?
    I require a specialist in this area to unravel my problem.
    Maybe that’s you! Having a look ahead to look you.

  7. I don’t even know how I ended up here, but I thought this
    post was great. I do not know who you are but definitely you are going to
    a famous blogger if you are not already 😉 Cheers!

  8. Oh my goodness! Incredible article dude! Thank you, However I am having issues with your RSS.
    I don’t know why I cannot join it. Is there anyone else having
    the same RSS problems? Anyone who knows the answer will you kindly respond?
    Thanx!!

  9. I am not sure where you’re getting your information, but great
    topic. I needs to spend some time learning much more
    or understanding more. Thanks for great information I was looking for this info for my mission.

  10. Hello there! I could have sworn I’ve been to this website before
    but after reading through some of the post I realized it’s new to me.
    Anyways, I’m definitely glad I found it and I’ll be
    bookmarking and checking back often!

  11. Hi! This post could not be written any better!
    Reading through this post reminds me of my
    old room mate! He always kept chatting about this.
    I will forward this post to him. Fairly certain he will have a good read.
    Many thanks for sharing!

  12. Hello there! This blog post couldn’t be written any better!
    Reading through this post reminds me of my previous roommate!
    He always kept preaching about this. I’ll send this article to him.
    Fairly certain he’s going to have a very good read. Many thanks for sharing!

    Feel free to visit my homepage; Buy Mushrooms

  13. Hi! I could have sworn I’ve been to this site
    before but after browsing through a few of the articles I realized
    it’s new to me. Anyways, I’m definitely pleased I discovered it and I’ll be book-marking it and checking back often!

  14. I received my bag yesterday or to They look and feel great for example I’m so pleased with my purchase blue jays Thank you for the bag and it was a pleasure doing business with you guys.

  15. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. alternatively the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. like the I highly recommend this site to anyone who’s looking for real jordans. in any event what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    [url=https://www.cheapsneakeronline.com/]authentic cheap jordans[/url]

  16. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. in addition to the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. including the I highly recommend this site to anyone who’s looking for real jordans. in any event what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    cheap jordans for sale https://www.retrocheapjordansshoes.com/

  17. Pingback: prednisone online
  18. Pingback: bupropion price
  19. Pingback: metformin price
  20. Pingback: lisinopril 2.5mg
  21. Pingback: generic fluoxetine
  22. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. or maybe a the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. prefer I highly recommend this site to anyone who’s looking for real jordans. situation what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    authentic cheap jordans https://www.realcheapretrojordanshoes.com/

  23. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. or else the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. prefer the I highly recommend this site to anyone who’s looking for real jordans. regardless what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    cheap real jordans https://www.cheapauthenticjordans.com/

  24. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. while well as the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. love the I highly recommend this site to anyone who’s looking for real jordans. in any event what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    cheap jordan shoes https://www.airretrojordans.com/

  25. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. in addition the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. decline I highly recommend this site to anyone who’s looking for real jordans. regardless what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    cheap jordan shoes https://www.cheaprealjordanshoes.com/

  26. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. also known as the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. enjoy the I highly recommend this site to anyone who’s looking for real jordans. direction what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    cheap jordan shoes https://www.cheaprealjordan.com/

  27. I’m always looking for web sites that sell real jordans. I’ve purchased several jordans over the last year. or the jordans are always perfect, the shipping time is very prompt, and the communication is excellent. much I highly recommend this site to anyone who’s looking for real jordans. regardless what I especially like it is the information they have on their Release Dates page. This really helps me stay in tune with what’s going on in the world of jordans.
    buy cheap jordans https://www.cheapretrojordan.com/

  28. I received my shoes yesterday. This is the first time ordering shoes from this website and I am definitely satisfied with them. potentially I would give this website a 20 on a scale from 1-10 and would certainly recommend this site to all. decline I will definitely be purchasing more items in the future. in any event It has been a pleasure.
    cheap retro jordans https://www.cheapauthenticjordanshoes.com/

  29. I received my jordans yesterday. This is the first time ordering shoes from this website and I am definitely satisfied with them. or possibly I would give this website a 20 on a scale from 1-10 and would certainly recommend this site to all. particularly the I will definitely be purchasing more items in the future. regardless It has been a pleasure.
    cheap jordan shoes https://www.realjordansshoes.com/

  30. It is appropriate time to make some plans for the future and it’s time to
    be happy. I have read this post and if I
    could I want to suggest you some interesting things or advice.
    Perhaps you can write next articles referring to this article.

    I wish to read more things about it!

  31. I like what you guys are usually up too. This sort
    of clever work and reporting! Keep up the very good works guys I’ve included you guys to my own blogroll.

  32. Magnificent goods from you, man. I have be mindful your stuff previous to and
    you are just extremely excellent. I actually like what you have got here, really like what you’re stating
    and the way by which you assert it. You are making it enjoyable and you still care for to stay it
    sensible. I can’t wait to read far more from you.
    This is really a terrific website.

  33. I received my jordans yesterday. This is the first time ordering shoes from this website and I am definitely satisfied with them. potentially I would give this website a 20 on a scale from 1-10 and would certainly recommend this site to all. just like I will definitely be purchasing more items in the future. manner in which It has been a pleasure.
    cheap jordan shoes for sale https://www.authenticcheapjordans.com/

  34. Admiring the commitment you put into your site and in depth information you provide.
    It’s great to come across a blog every once in a while that isn’t the same out
    of date rehashed material. Fantastic read! I’ve bookmarked
    your site and I’m adding your RSS feeds to my Google account.

  35. you are truly a just right webmaster. The site loading speed is amazing.

    It sort of feels that you’re doing any unique trick.
    Moreover, The contents are masterpiece. you’ve performed a
    fantastic job on this matter!

  36. Woah! I’m really loving the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance”
    between usability and visual appearance. I must say you have done a fantastic job with this.
    Also, the blog loads very quick for me on Chrome. Excellent Blog!

  37. I received my jordans yesterday. This is the first time ordering shoes from this website and I am definitely satisfied with them. potentially I would give this website a 20 on a scale from 1-10 and would certainly recommend this site to all. like I will definitely be purchasing more items in the future. situation It has been a pleasure.
    cheap real jordans online https://www.cheaprealjordansonline.com/

  38. Hi there! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no data
    backup. Do you have any solutions to prevent hackers?

  39. This design is spectacular! You certainly know how to keep a reader entertained.
    Between your wit and your videos, I was almost moved to start my own blog
    (well, almost…HaHa!) Fantastic job. I really enjoyed
    what you had to say, and more than that, how you presented it.
    Too cool!

  40. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each
    time a comment is added I get several emails with the same comment.
    Is there any way you can remove people from that service?
    Thanks!

  41. My partner and I absolutely love your blog and find nearly all of your post’s to be what precisely I’m looking for.
    can you offer guest writers to write content to suit your needs?
    I wouldn’t mind producing a post or elaborating on a few of the subjects you write
    related to here. Again, awesome blog!

  42. Hello, Neat post. There is a problem together with your
    website in web explorer, would test this? IE still is the market chief and a huge section of people will omit your great writing because of this problem.

  43. Hi, I do believe this is a great web site. I
    stumbledupon it 😉 I’m going to return once again since i have book marked it.

    Money and freedom is the greatest way to change, may you be rich and
    continue to help others.

  44. I’m extremely impressed with your writing skills as smartly as with the
    format for your weblog. Is that this a paid theme or did you customize it
    yourself? Either way stay up the nice quality writing,
    it’s uncommon to peer a nice blog like this one today..

  45. You actually make it seem so easy together with your presentation but I to find this
    matter to be actually one thing that I believe I’d by
    no means understand. It kind of feels too complicated and extremely vast for me.
    I’m looking ahead to your subsequent put up, I will attempt to get the grasp of it!

  46. Having read this I thought it was extremely enlightening.
    I appreciate you spending some time and energy to put this content together.

    I once again find myself personally spending way too much time both reading and leaving comments.
    But so what, it was still worthwhile!