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

Leave a Reply

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

Back to top