Calling a specific function alone in javascript or jquery

Question!

i have a piece of code like this.

// HTML file
<div class="box" ng-click="displayinfo()">
    click here to display info about this page.
    <div class="content" ng-click="displaytext()">
        Click here to display text.
    </div>
    click here to display info about this page.
</div>

// JS file
$scope.displayinfo = function()
{
    alert('info');
}
$scope.displaytext = function()
{
    alert('Text');
}

the thing is while clicking on 'click here to display text', it is calling both functions and displaying 'Text' and 'info'. but i dnt want to display 'info' here. i cannot change the html div structure.

how to do that?



Answers
It's a little hidden in the docs, but if you look here: http://docs.angularjs.org/api/ng.directive:ngClick

You can see that parameters it mentions an $event object. So your html will become:

<div class="box" ng-click="displayinfo($event)">
    click here to display info about this page.
    <div class="content" ng-click="displaytext($event)">
        Click here to display text.
    </div>
    click here to display info about this page.
</div>

and then your javascript will become:

$scope.displayinfo = function($event)
{
    $event.stopPropagation();
    alert('info');
}
$scope.displaytext = function($event)
{
    $event.stopPropagation();
    alert('Text');
}

jsfiddle: http://jsfiddle.net/rtCP3/32/



Instead calling functions there inline use jquery to solve this issue:

$('.box').click(function(){
    displayinfo();
});

$('.content').click(function(e){
    e.stopPropagation(); //<-------------------this will stop the bubbling
    displaytext();
});

demo code for e.stopPropagation(): http://jsfiddle.net/HpZMA/

var a = "text for info";
$('.box').click(function(){
    $(this).append(a)
});

var b = "text for info";
$('.content').click(function(e){
    e.stopPropagation(); //<-------------------this will stop the bubbling
    $(this).append(b)
});
By : Jai


For native javascript solution you need to pass event as argument to your 2 methods in order to prevent the event from propagating

<div class="box" onclick="displayinfo(event)"> 

Then change js to:

var displayinfo = function(event) {
    event.cancelBubble = true
    alert('info')
}

var displaytext = function(event) {
    event.cancelBubble = true
    alert('text')
}

DEMO: http://jsfiddle.net/MvgTd/



This video can help you solving your question :)
By: admin