Reputation: 956
Code is below, I'm stuck to the reasoning behind this but the focus / blur events are only getting activated on the 2nd time the event happens. I'm not worried about anything else currently but the reasoning as to why this is only getting ran on anything after the first time.
JS:
var App = function () {
this.page = window.location.pathname.split("/public/portal/")[1].split("/")[0];
}
$.extend(App.prototype, {
// This will set the variables in the box and display / hide
setVariables: function (ele, vars) {
this.variables = vars || variables;
var list = $("#page_variables .text_variables");
// Create the variable box
$('li', list).remove(); // first remove all variables currently in the box
console.log(ele);
ele.bind('focus', function () {
list.fadeIn();
})
.bind('blur', function () {
list.fadeOut();
});
}
});
(function ($, undefined) {
$(".tvar_text").focus(function () {
port.setVariables($(this), null);
});
})(jQuery);
HTML:
<div id="page_variables">
<div class="text_variables" style="display:none">
<ul>
<strong style="text-decoration: underline;">VARIABLES</strong>
<li>{provider}</li>
<li>{date}</li>
<li>{callerid}</li>
<li>{time}</li>
<li>{location}</li>
<li>{recipient}</li>
<li>{misc1}</li>
<li>{misc2}</li>
<li>{misc3}</li>
<li>{misc4}</li>
</ul>
</div>
</div>
<textarea class="tvar_text" name="Vtmpl" cols="50" rows="10" style="min-height: 200px; overflow: hidden; resize: none; height: 50px;"></textarea>
Upvotes: 0
Views: 55
Reputation: 700182
That's because you are binding the focus event from a focus event handler. (A .focus(...)
call does the same as a .bind('focus', ...)
call.)
The first time that the focus event happens, it will bind events for showing and hiding the list (but not show the list).
The first time the blur event happens the event handler works fine, but as the list isn't visible yet you don't see that.
The second time the focus event happens, it will show the list.
Also, every time the focus event happens, it will add another set of event handlers for showing and hiding the list. If you show and hide the list a few times, it will start behaving strange and/or start getting sluggish. Eventually it will crash/freeze the browser, becase there are too many event handlers trying to show or hide the list at the same time.
To call the function on each element that matches the selector, you would use the each
method:
$(".tvar_text").each(function(i, el){
port.setVariables($(el), null);
});
Upvotes: 2