Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a specific function alone in javascript or jquery

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?

like image 969
JSAddict Avatar asked Jun 27 '26 21:06

JSAddict


2 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/

like image 74
Mathew Berg Avatar answered Jun 29 '26 09:06

Mathew Berg


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)
});
like image 31
Jai Avatar answered Jun 29 '26 10:06

Jai