Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button click not firing when leaving textarea

I am currently making a textarea that will auto expand. This seems to work fine however the button click never seems to fire when the textarea is expanded. I am also using angularjs. Here is my code

HTML:

<body >
    <div my-dir></div>
</body>

Javascript:

var app = angular.module('myApp',[]);

app.directive('myDir', function(){
    return {
        restrict:'A',
        template:'<textarea id="textarea1">'+'</textarea>' + '<button ng-click="clicked()">Click me</button><textarea id="textarea2"></textarea>',
        link:function(scope){
            scope.clicked = function(){
                 alert("click worked");
            }
        }
    }
});

If anybody could help me find a workaround or explain why exactly this is happening that would be greatly appreciated.

Link to codepen: http://codepen.io/anon/pen/mJrjpP

like image 906
BobDoleForPresident Avatar asked Sep 28 '22 21:09

BobDoleForPresident


2 Answers

When the textarea is focused the button moves down a bit, and when you click the button the textareas blur event fires first, moving the button up, so the click never happens because the button moved.

The solution is to make sure the button stays put, using CSS positioning, or as noted in the comment by gyantasaurus below

<button ng-mousedown="clicked()">Click me</button>
like image 96
adeneo Avatar answered Sep 30 '22 10:09

adeneo


The problem is that, when the textarea loses focus, it resizes and the button moves so, if you've removed focus from the textarea by clicking on the button, the click event, which consists of a mousedown and mouseup event, will never fire as, when the mouse is released, the cursor is no longer over the button.

You can test this yourself by focussing on the textarea, clicking down on the button, moving your cursor to the button's new position and then releasing your mouse button.

One solution, therefore, would be simply to use the muosedown event, rather than the click event.

like image 35
Shaggy Avatar answered Sep 30 '22 09:09

Shaggy