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,

Rajeev K Tomy

274 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?

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top