Keep textarea open if change event otherwise animate it on blur - javascript

What I'm trying to do is this:
You click in a textarea, and it'll expand to 100px. Normally it's at 50px. If you click outside (or trigger the blur event after clicking in the textarea...) it should go back to it's normal 50px height.
If you trigger the change event by entering something into the textarea, I want to be able to click on the submit button without it triggering the blur (to move it back to 50px).
Am I on the right track?
var expandTextarea = function() {
$('.js-textarea-slide').on('click', function(e) {
var typed = false;
$(this).change(function() {
typed = true;
});
$(this).animate({
height: '100'
}, 0);
});
$('.js-textarea-slide').blur(function(typed, e) {
if (!typed) {
alert('yo');
return false;
} else {
$(this).animate({
height: '50'
}, 0);
}
});
};
http://jsfiddle.net/khE4A/

http://jsfiddle.net/khE4A/4/
var expandTextarea = function() {
//Note that this is in a scope such that the click, blur and change handlers can all see it
var typed = false;
$('.js-textarea-slide').on('click', function(e) {
//If you bind the change handler in here, it will be bound every time the click event
//is fired, not just once like you want it to be
$(this).animate({
height: '100'
}, 0);
}).change(function() {
typed = true;
});
//Note that I got rid of typed and e.
//If typed were included here, it would not have the value of the typed on line 4.
//Rather, it would have the value of whatever jQuery's event processing passes as the first
//parameter. In addition, it would hide the typed on line 4 from being accessible since
//they have the same name.
//Also, I got rid of the e parameter because it's not used, and in JavaScript, it's perfectly
//acceptable to have a paramter calling/definition count mismatch.
$('.js-textarea-slide').blur(function() {
if (!typed) {
$(this).animate({
height: '50'
}, 0);
}
});
};
//Since expandTextarea doesn't depend on the context it's called from, there's no need to wrap it
//in an extra function.
$(expandTextarea);​
Note that this follows the logic you described in your question, not what your code was trying to do. Anyway, a few important changes:
Your change event would be bound every time the textarea was clicked instead of once. For example, if you clicked on the textarea 3 times, you would bind the event 3 times instead of just the 1 time required.
Also, the part that actually made the code broken was that typed was out of scope of the blur handler. Giving a callback a parameter with a certain name does not pull that variable into scope. In fact, it would mask it if the variable had been in a previously accessible scope.
Another [pedantic] thing:
$(function() {
expandTextarea();
});​
The function wrapping is unnecessary. As expandTextarea does not use this, you can use the function directly:
$(expandTextarea);
Anyway, given the description of the problem in your question, I believe what you're looking for is: http://jsfiddle.net/khE4A/2/

Related

Dynamically changing a checkbox doesn't trigger onChange?

Note: jQuery is not an option.
I want to detect a change in the state of a checkbox, but the onChange event doesn't seem to fire when I do this:
document.getElementById('myCheckBox').addEventListener('change',function() {
console.log('Changed!');
});
document.getElementById('someLink').onClick = function() {
// toggle checkbox
document.getElementById('myCheckBox').checked = !document.getElementById('myCheckBox').checked;
};
When I click #someLink the change event is not fired. I could add another listener to #myLink, but then if I add other links that check the same box I have to add more listeners. I want one listener for a checkbox change event. Again, jQuery is not an option, I need vanilla JS.
EDIT: Sorry if I did not make this more clear, but I want to avoid adding complexity to each link that will check this box. So ideally (and maybe the answer is that this is impossible) I don't want to have to alter the link/click logic at all. I want to be able to change the .checked property anywhere in the code and have it be detected without additional logic at each change (if possible).
UPDATE:
Okay so there is apparently no way to do this nicely without altering the onClick logic, so (like some kind of animal) I ended up brute forcing the problem as follows:
function mySentinel() {
if(document.getElementById('myCheckBox').checked) {
console.log("I've been checked!");
return;
}
setTimeout("mySentinel()",100);
}
// then call this somewhere in the on document load section...
mySentinel();
You can add some sort of timeout if you want also:
function mySentinel(var i) {
if(document.getElementById('myCheckBox').checked) {
console.log("I've been checked!");
return;
}
if(i <= 0) {
console.log("Time out. Still not checked");
}
i--;
setTimeout("mySentinel("+i+")",100);
}
// then call this somewhere in the on document load section...
// 60 second timeout (some math can make the argument look nicer)
mySentinel(600);
That is correct, changing the value or checked state of an input programatically does not fire the event handlers.
You'll have to trigger the event as well with javascript
document.getElementById('myCheckBox').addEventListener('change',function() {
console.log('Changed!');
});
document.getElementById('someLink').onclick = function() {
var box = document.getElementById('myCheckBox')
box.checked = !box.checked;
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
box.dispatchEvent(evt);
} else {
box.fireEvent("onchange");
}
};
and note that's it's onclick (all lowercase)
FIDDLE
EDIT
I want to avoid adding complexity to each link that will check this box.
So ideally ... I don't want to have to alter the link/click logic at all.
I want to be able to change the .checked property anywhere in the code and have it be detected without additional logic at each change (if possible).
And that's not really possible, without using horrible hacks with intervals etc.
When the checked state is changed programatically the event handler isn't triggered at all, because that would really be a huge issue in most cases, and much harder to work around the opposite scenario, where you just trigger the event handler manually instead, and that is really the only way to do it.
Of course, you can make it a lot more convenient using classes and external function and such
document.getElementById('myCheckBox').addEventListener('change',function() {
console.log('Changed!');
});
var links = document.querySelectorAll('.someLinkClass');
for (var i = links.length; i--;) {
links[i].addEventListener('click', triggerChange, false);
}
function triggerChange() {
var box = document.getElementById('myCheckBox')
box.checked = !box.checked;
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
box.dispatchEvent(evt);
} else {
box.fireEvent("onchange");
}
};
and anytime you add a link, you just add that class
Change the checkbox
Change the checkbox again
Change the checkbox even more
etc.
If you want to add more links that will trigger the checkbox, create a class name for them and use getElementByClass('classname')
Use onclick in your html, not js. Example: <div onclick="doSomething()"></div>
Just use an if/else statement for the check/uncheck:
if(document.getElementById('myCheck').checked){document.getElementById("myCheck").checked = false;} else{document.getElementById("myCheck").checked = true;}
I think jQuery have a change event. And you don't use it in the good way.
Read this page: http://api.jquery.com/change/
and this: jQuery checkbox change and click event
When any change occurs in the checkbox, jQuery event function is called. And then you can write anything in this event function
You can invoke/trigger an event but its not as easy as it seems, especially when you have to deal with internet explorer.
The cleanest solution is to put your event into its own function, then call it where you need it.
function handleEvent(){
console.log('Changed!');
}
documentent.getElementById('myCheckBox').addEventListener('change',function() {
handleEvent()
});
document.getElementById('someLink').onClick = function() {
// toggle checkbox
document.getElementById('myCheckBox').checked = !document.getElementById('myCheckBox').checked;
handleEvent();
};

Detect div movement nd run function at certain intervals jQuery

On my website I have a a div (.wrapper) that moves co ordinates absolutely when the mouse wheel is scrolled, or the user uses his arrow keys/spacebar etc.
At certain points, say when the div.wrapper is -1000 pixels left, Id like a function to happen.
Is there anyway I can check for this without using an interval?
setInterval(function(){
if($('.wrapper').css('left') <= 100 + 'px'){
alert('foo');
} else {
alert ('bar');
};
}, 5000);
There's no event to detect changes in CSS properties. The usual way to do this is to put the call the handler explicitly after updating the left property.
You can move the code that changes the value into a separate function:
function setLeft(left){
$('.wrapper').css('left', left);
if($('.wrapper').css('left') <= 100 + 'px'){
alert('foo');
} else {
alert ('bar');
};
}
If you wanted to you could trigger inside the setLeft function and put the checking code into an event handler.
Another thing works is creating a wrapper function for .css that triggers the event:
var originalCssFunction = $.prototype.css;
$.prototype.css = function(){
originalCssFunction.apply(this, arguments);
// Check conditions and trigger event
}

Toggling click handlers in Javascript

I have an HTML button to which I attach an event, using jQuery's bind(), like so:
$('#mybutton').bind('click', myFirstHandlerFunction);
In myFirstHandlerFunction, I'd like this handler to replace itself with a new handler, mySecondHandlerFunction, like this:
function myFirstHandlerFunction(e) {
$(this).unbind('click', myFirstHandlerFunction).bind('click', mySecondHandlerFunction);
}
In the second click handler, mySecondHandlerFunction, I'd like to toggle the button back to its original state: unbind the mySecondHandlerFunction handler and reattach the original handler, myFirstHandlerFunction, like so:
function mySecondHandlerFunction(e) {
$(this).unbind('click', mySecondHandlerFunction).bind('click', myFirstHandlerFunction);
}
This works great, except for one small detail: because the click event has not yet propagated through each of the button's click handlers, the click event is passed on to the button's next click handler, which happens to be the handler that was just bound in the previous handler. The end result is mySecondHandlerFunction being executed immediately after myFirstHandlerFunction is executed.
This problem can be easily solved by calling e.stopPropagation() in each handler, but this has the negative side-effect of cancelling any other click handlers that may have been attached independently.
Is there a way to safely and and consistently toggle between two click handlers, without having to stop the propagation of the click event?
Update: Since this form of toggle() was removed in jQuery 1.9, the solution below does not work anymore. See this question for
alternatives.
It looks like toggle() would solve your problem:
$("#mybutton").toggle(myFirstHandlerFunction, mySecondHandlerFunction);
The code above will register myFirstHandlerFunction and mySecondHandlerFunction to be called on alternate clicks.
Just use a boolean to toggle the functionality of the handler, there's no need to juggle which handler is listening:
$('#mybutton').bind('click', myHandlerFunction);
var first = true;
function myHandlerFunction(e) {
if(first){
// Code from the first handler here;
}else{
// Code from the second handler here;
}
first = !first; // Invert `first`
}
This solution is a hack, but it is short and sweet for your rough work:
$('#myButton').click(function() {
(this.firstClk = !this.firstClk) ? firstHandler(): secondHandler();
});
It's a hack because it's putting a new property directly onto this which is the click-target HTML DOM element, and that's maybe not best practice. However, it thus avoids creates any new globals, and it can be used unchanged on different buttons simultaneously.
Note that the first part of the ternary operation uses = and not == or ===, i.e. it's an assignment, not a comparison. Note also that the first time the button is clicked, this.firstClk is undefined but is immediately negated, making the first part of the ternary operation evaluate to true the first time.
Here's a working version:
$('#a > button').click(function() {(this.firstClk = !this.firstClk) ? a1(): a2();});
$('#b > button').click(function() {(this.firstClk = !this.firstClk) ? b1(): b2();});
function a1() {$('#a > p').text('one');}
function a2() {$('#a > p').text('two');}
function b1() {$('#b > p').text('ONE');}
function b2() {$('#b > p').text('TWO');}
div {display: inline-block;width: 10em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a"><p>not yet clicked</p><button>click</button></div>
<div id="b"><p>NOT YET CLICKED</p><button>CLICK</button></div>
I was looking at this today, and realized there was still not a way to do this without a global variable listed. I came up with the following to add locations to an ESRI basemap, but it would work generally too:
function addLocationClickHandler() {
var addLocationClick = overviewMap.on('click', function (event) {
addLocationClick.remove();
})
$('#locationAddButton').one('click', function (cancelEvent) {
addLocationClick.remove();
$('#locationAddButton').on('click', addLocationClickHandler)
});
}
$('#locationAddButton').on('click', addLocationClickHandler)
This should allow you to put something else in the section where you overwrite the click handler and not necessitate a global variable.
This would help add data-click-state attribute on your button
$(document).ready(function() {
$('#mybutton').on('click', function() {
if ($(this).attr('data-click-state') == 1) {
$(this).attr('data-click-state', 0)
myFirstHandlerFunction();
} else {
$(this).attr('data-click-state', 1)
mySecondHandlerFunction();
}
});
});
Like this:
$(this).bind('click', myMasterHandler);
handler = 0;
function myMasterHandler(e) {
if(handler == 0) {
myFirstHandler(e);
handler = 1;
} else {
mySecondHandler(e);
handler = 0;
}
}

jQuery: Get reference to click event and trigger it later?

I want to wrap an existing click event in some extra code.
Basically I have a multi part form in an accordion and I want to trigger validation on the accordion header click. The accordion code is used elsewhere and I don't want to change it.
Here's what I've tried:
//Take the click events off the accordion elements and wrap them to trigger validation
$('.accordion h1').each(function (index, value) {
var currentAccordion = $(value);
//Get reference to original click
var originalClick = currentAccordion.click;
//unbind original click
currentAccordion.unbind('click');
//bind new event
currentAccordion.click(function () {
//Trigger validation
if ($('#aspnetForm').valid()) {
current = parseInt($(this).next().find('.calculate-step').attr('data-step'));
//Call original click.
originalClick();
}
});
});
jQuery throws an error because it's trying to do this.trigger inside the originalClick function and I don't think this is what jQuery expects it to be.
EDIT: Updated code. This works but it is a bit ugly!
//Take the click events off the accordion elements and wrap them to trigger validation
$('.accordion h1').each(function (index, value) {
var currentAccordion = $(value);
var originalClick = currentAccordion.data("events")['click'][0].handler;
currentAccordion.unbind('click');
currentAccordion.click(function (e) {
if ($('#aspnetForm').valid()) {
current = parseInt($(this).next().find('.calculate-step').attr('data-step'));
$.proxy(originalClick, currentAccordion)(e);
}
});
});
I think this:
var originalClick = currentAccordion.click;
Isn't actually doing what you think it is - you're capturing a reference to the jQuery click function, rather than event handler you added, so when you call originalClick() it's equivalent to: $(value).click()
I finally came up with something reliable:
$(".remove").each(function(){
// get all our click events and store them
var x = $._data($(this)[0], "events");
var y = {}
for(i in x.click)
{
if(x.click[i].handler)
{
y[i] = x.click[i].handler;
}
}
// stop our click event from running
$(this).off("click")
// re-add our click event with a confirmation
$(this).click(function(){
if(confirm("Are you sure?"))
{
// if they click yes, run click events!
for(i in y)
{
y[i]()
}
return true;
}
// if they click cancel, return false
return false;
})
})
This may seem a bit weird (why do we store the click events in the variable "y"?)
Originally I tried to run the handlers in x.click, but they seem to be destroyed when we call .off("click"). Creating a copy of the handlers in a separate variable "y" worked. Sorry I don't have an in depth explanation, but I believe the .off("click") method removes the click event from our document, along with the handlers.
http://www.frankforte.ca/blog/32/unbind-a-click-event-store-it-and-re-add-the-event-later-with-jquery/
I'm not a jQuery user, but in Javascript, you can set the context of the this keyword.
In jQuery, you use the $.proxy() method to do this.
$.proxy(originalClick, value);
originalClick();
Personally, I'd look at creating callback hooks in your Accordion, or making use of existing callbacks (if they exist) that trigger when opening or closing an accordion pane.
Hope that helps :)
currentAccordion.click is a jQuery function, not the actual event.
Starting with a brute-force approach, what you'd need to do is:
Save references to all the currently bound handlers
Unbind them
Add your own handler, and fire the saved ones when needed
Make sure new handlers bound to click are catched too
This looks like a job for an event filter plugin, but I couldn't find one. If the last point is not required in your application, then it's a bit simpler.
Edit: After some research, the bindIf function shown here looks to be what you'd need (or at least give a general direction)

How to send mouseover event to parent div?

I have a Div in which there is a text input, like this:
<div id="parentDive" class="parent">
<input id="textbox"></input>
</div>
I have assigned a functionality to the Div mouseover event and mouseout event by means of JQuery, but when I move my mouse over the text input, it calls mouseout event while it's in the DIV.
How to solve this problem? Should I send the event to the parent? How?
Use the jQuery .hover() method instead of binding mouseover and mouseout:
$("#parentDive").hover(function() {
//mouse over parent div
}, function() {
//mouse out of parent div
});
$("#textbox").hover(function() {
//mouse over textbox
}, function() {
//mouse out of textbox
});
Live test case.
The .hover() is actually binding the mouseenter and mouseleave events, which are what you were looking for.
I suggest to you to use .hover() not .mouseover() and .mouseout() here is a live working example
http://jsfiddle.net/DeUQY/
$('.parent').hover(function(){
alert('mouseenter');
},function(){
alert('mouseleave');
}
);
You need to use a few steps to make that work.
First, create the parent hover functions which would be enter() and exit(). These are setup using the hover() function. Then create the children enterChild() and exitChild() function. The children just change a flag that allows you to know whether a child is being hovered and thus the parent is still being considered to be hovered.
Whatever you want to do in the exit() function, you cannot do it immediately because the events arrive in the correct order for a GUI, but the wrong order for this specific case:
enter parent
exit parent
enter child
exit child
enter parent
exit parent
So when your exit() function gets called, you may be entering the child right after and if you want to process something when both the parent and child are exited, just acting on the exit() will surely be wrong. Note that the browser is written in such a way that an exit event always happens if an enter event happened. The only exception may be if you close the tab/window in which case they may forfeit sending more events.
So, in the parent exit() function we make use of a setTimeout() call to make an asynchronous call which will happen after the enter() function of a child happens. This means we can set a flag there and test it in the asynchronous function.
MyNamespace = {};
MyNamespace.MyObject = function()
{
var that = this;
// setup parent
jQuery(".parentDiv").hover(
function()
{
that.enter_();
},
function()
{
that.exit_();
});
// setup children
jQuery(".parentDiv .children").hover(
function()
{
that.enterChild_();
},
function()
{
that.exitChild_();
});
}
// couple variable members
MyNamespace.MyObject.prototype.parentEntered_ = false;
MyNamespace.MyObject.prototype.inChild_ = false;
MyNamespace.MyObject.prototype.enter_ = function()
{
// WARNING: if the user goes really fast, this event may not
// happen, in that case the childEnter_() calls us
// so we use a flag to make sure we enter only once
if(!this.parentEntered_)
{
this.parentEntered_ = true;
... do what you want to do when entering (parent) ...
}
};
// NO PROTOTYPE, this is a static function (no 'this' either)
MyNamespace.MyObject.realExit_ = function(that) // static
{
if(!that.inChild_)
{
... do what you want to do when exiting (parent) ...
that.parentEntered_ = false;
}
};
MyNamespace.MyObject.prototype.exit_ = function()
{
// need a timeout because otherwise the enter of a child
// does not have the time to change inChild_ as expected
setTimeout(MyNamespace.MyObject.realExit_(this), 0);
};
// detect when a child is entered
MyNamespace.MyObject.prototype.enterChild_ = function()
{
this.inChild_ = true;
this.enter_(); // in case child may be entered directly
};
// detect when a child is exited
MyNamespace.MyObject.prototype.exitChild_ = function()
{
this.inChild_ = false;
// We cannot really do this, although in case the child
// is "exited directly" you will never get the call to
// the 'exit_()' function; I'll leave as an exercise for
// you in case you want it (i.e. use another setTimeout()
// but save the ID and clearTimeout() if exit_() is not
// necessary...)
//this.exit_()
};

Categories

Resources