Detecting when jQuery's hide() method is fired on an element - javascript

Is it possible to detect when jQuery has fired it's .hide() method on an element?
I tried binding to the hide event on such an element:
$('div').bind('hide', function(){
alert("Hidden");
})
but the alert doesn't display.

You can do it by overriding JQuery's hide method:
var oldHide = $.fn.hide;
$.fn.hide = function() {
alert("Hidden");
oldHide.apply(this, arguments);
}
...as shown here.

all the time? or just for debugging?
you could just use the call back function to write something to the log.
$( '#my-id' ).hide( duration, function(){ console.log( 'fired!' ); } );

Related

JQuery/JavaScript: Enable and disable div

this is my code example:
$( "#new_warehouse" ).onClick(function() {
$('.js-dependent-fields:hidden').children().prop('disabled', true);
});
It adds a "disabled" to all childs of my js-dependent-fields div, if style="display: none;". How can I revert this when the js-dependent-fields div gets visible?
Many thanks in advance!
You should use correctly .on() listener with .click() event with a callback function in the prop() method:
$( "#new_warehouse" ).on('click', function() {
$('.js-dependent-fields').children().prop('disabled', function(){
return $(this).is(':hidden');
});
});
Thing to notice is that the target element is a class selector so it would return a collection so, we have to look for each one with the $(this) and check if it is :visible.
Perhaps a more apt code would be
$( "#new_warehouse" ).onClick(function() {
$('.js-dependent-fields').children().prop('disabled',
$('.js-dependent-fields').is(':hidden') ?
true : false );
});
You can reverse the effect using :visible pseudo class selector. But for your need you can use like this:
$('.js-dependent-fields:hidden').children().prop('disabled',
$('.js-dependent-fields').is(':hidden')//sets true if hidden else false
);

JS click in a Jquery function on load

I have a JS function that I want to automatic click in a jquery.click link when page loads.
How can I make it work?
Fiddle
When page loads I want to see the alert, no click in the link needed.
js:
window.onload = function(){
document.getElementsByClassName("c").click();
}
$(".c").click(function(){
alert("ok");
});
html:
test
you need to attach click event before trigger event.
DEMO
Change
document.getElementsByClassName("c")
to
document.getElementsByClassName("c")[0]
Use Below code
$(document).ready(function(){
$(".c").click(function(){
alert("ok");
});
});
window.onload = function(){
document.getElementsByClassName("c")[0].click();
// Or use jQuery trigger
// $(".c").trigger('click')
}
DEMO HERE
trigger click on document.ready
$('document').ready(function(){
$(".c").click(function(){
alert("ok");
});
$('.c').trigger('click');
});
Trigger event right after you create handler
$(function(){
$(".c").click(function(){
alert("ok");
}).click();
});
DEMO
Try this way
$(document).ready(function(){
$(".c").trigger('click');
});
getElementsByClassName Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.
To assign a click handler, either you will have to iterate through nodelist or just assign event to first element
Try this:
window.onload = function () {
document.getElementsByClassName("c")[0].click();
};
$(".c").click(function () {
alert("ok");
});
So you can push your alert into a function :
function callAlert() {
alert('a');
}
And you can change the event click like this :
$(".c").click(callAlert);
Finally you can call the alert function when page loads like this :
$('document').ready(function(){
callAlert(); // call here
});
Code :
$('document').ready(function(){
callAlert();
$(".c").click(callAlert);
});
function callAlert() {
alert('a');
}

ajax on elements not working for appended content

I have the following javascript:
<script>
$(document).ready(function() {
$('[class^="commentbubble_"]').click(function () {
var ID = $(this).attr('class').replace('commentbubble_', '');
$('.commentform_'+ID).toggle();
$('#commentsection').masonry( 'reload' );
});
});
</script>
It works for the first page of results...but for newly appended, it won't work. Is there a way to ensure this function works on newly appended content?
Thank you.
You can try with delegation the event to its parent which was available on page load or $(document) itself with .on() handler:
$(document).ready(function() {
$(document).on('click', '[class^="commentbubble_"]', function () {
var ID = $(this).attr('class').replace('commentbubble_', '');
$('.commentform_'+ID).toggle();
$('#commentsection').masonry( 'reload' );
});
});
$().ready only works on the current elements
When you append an element you need bind is click event
Since you are appending data on ajax load after page is loaded, So you need to use .on event handler to bind any event on the element instead of .click event.
Syntax is :
.on( events [, selector ] [, data ], handler(eventObject) )
So your script will be something like this :
<script>
$(document).ready(function() {
$('document).on('click','[class^="commentbubble_"]',function () {
var ID = $(this).attr('class').replace('commentbubble_', '');
$('.commentform_'+ID).toggle();
$('#commentsection').masonry( 'reload' );
});
});
</script>
For more reference, refer http://api.jquery.com/on/
use live
('[class^="commentbubble_"]').live ('click', function () {
Note:
live is deprecated, use on as suggested by #Jai

How Store and Disable Event of another element Temporary

I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.
I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"
I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.
Please help and advice!
$(A).hover();
$(b).click(
if($.hasData($(A)[0])){ // if A has event,
//STORE all the event A has, and disable
}else{
//ENABLE the stored event for A
}
);
Try this
var hoverme = function() {
alert('Hover Event Fired');
};
$('.A').hover(hoverme);
var i = 0;
$('.B').on('click', function(){
if(i%2 === 0){
// Unbind event
$('.A').off('hover');
}
else{
// Else bind the event
$('.A').hover(hoverme);
}
i++;
});
Check Fiddle
I think that what you want to do is something like this (example for JQuery 1.7.2):
$("#a").hover(function(){alert("test")});
$("#a")[0].active=true;
$("#b").click(function(){
if($("#a")[0].active){
$("#a")[0].storedEvents = [];
var hoverEvents = $("#a").data("events").mouseover;
jQuery.each(hoverEvents , function(key,handlerObj) {
$("#a")[0].storedEvents.push(handlerObj.handler);
});
$("#a").off('hover');
}else{
for(var i=0;i<$("#a")[0].storedEvents.length;i++){
$("#a").hover($("#a")[0].storedEvents[i]);
}
}
$("#a")[0].active = ($("#a")[0].active)==false;
});​
JSFiddle Example
But there are a couple of things that you must have in consideration:
This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.
I hope that this helps.
EDIT:
data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.
You could try having a variable that is outside the scope of functions a and b, and use that variable to trigger the action to take in function b on function a.
var state;
var a = function() {
if(!state) {
state = true;
// Add hover action and other prep. I'd create a third function to handle this.
console.log(state);
};
var b = function() {
if(state) {
state = false;
// Do unbinding of hover code with third function.
} else {
state = true;
// Do whatever else you needed to do
}
}
Without knowing more about what you're trying to do, I'd try something similar to this.
It sounds like you want to disable the click hover event for A if B is clicked.
$("body").on("hover", "#a", function(){
alert("hovering");
});
$("#b").click( function(){
$("body").off("hover", "#a", function() {
alert("removed hovering");
});
});
You can use the jQuery off method, have a look at this fiddle. http://jsfiddle.net/nKLwK/1/
Define a function to assign to hover on A element, so in b click, call unbind('hover') for A element and in second click on b element define again a function to hover, like this:
function aHover(eventObject) {
// Todo when the mouse enter object. You can use $(this) here
}
function aHoverOut(eventObject) {
// Todo when the mouse leave the object. You can use $(this) here
}
$(A).hover(aHover, aHoverOut);
// ...
$(b).click(function(eventObject) {
if($.hasData($(A)[0])){ // if A has event,
$(A).unbind('mouseenter mouseleave'); // This is because not a event hover, jQuery convert the element.hover(hoverIn, hoverOut) in element.bind('mouseenter', hoverIn) and element.bind('mouseleave', hoverOut)
}else{
$(A).hover(aHover, aHoverOut);
}
});
There are provably better ways to do it, but this works fine, on document ready do this:
$("#a")[0].active=false;
$("#b").click(function(){
$("#a")[0].active = ($("#a")[0].active)==false;
if($("#a")[0].active){
$("#a").hover(function(){alert("test")});
}else{
$("#a").off('hover');
}
});
JSFiddle example
You can use .off function from jQuery to unbind the hover on your "a" element.
function hoverA() {
alert('I\'m on hover');
}
$('#a').hover( hoverA );
var active = true;
$('#b').on('click', function(){
if(active){
$('#a').off('hover');
active = false;
} else{
$('#a').hover(hoverA);
active = true;
}
});
Live demo available here : http://codepen.io/joe/pen/wblpC

How to write onshow event using JavaScript/jQuery?

I have an anchor tag on my page, I want an event attached to it, which will fire when the display of this element change.
How can I write this event, and catch whenever the display of this element changes?
This is my way of doing on onShow, as a jQuery plugin. It may or may not perform exactly what you are doing, however.
(function($){
$.fn.extend({
onShow: function(callback, unbind){
return this.each(function(){
var _this = this;
var bindopt = (unbind==undefined)?true:unbind;
if($.isFunction(callback)){
if($(_this).is(':hidden')){
var checkVis = function(){
if($(_this).is(':visible')){
callback.call(_this);
if(bindopt){
$('body').unbind('click keyup keydown', checkVis);
}
}
}
$('body').bind('click keyup keydown', checkVis);
}
else{
callback.call(_this);
}
}
});
}
});
})(jQuery);
You can call this inside the $(document).ready() function and use a callback to fire when the element is shown, as so.
$(document).ready(function(){
$('#myelement').onShow(function(){
alert('this element is now shown');
});
});
It works by binding a click, keyup, and keydown event to the body to check if the element is shown, because these events are most likely to cause an element to be shown and are very frequently performed by the user. This may not be extremely elegant but gets the job done. Also, once the element is shown, these events are unbinded from the body as to not keep firing and slowing down performance.
You can't get an onshow event directly in JavaScript. Do remember that the following methods are non-standard.
IN IE you can use
onpropertychange event
Fires after the property of an element
changes
and for Mozilla
you can use
watch
Watches for a property to be assigned
a value and runs a function when that
occurs.
You could also override jQuery's default show method:
var orgShow = $.fn.show;
$.fn.show = function()
{
$(this).trigger( 'myOnShowEvent' );
orgShow.apply( this, arguments );
return this;
}
Now just bind your code to the event:
$('#foo').bind( "myOnShowEvent", function()
{
console.log( "SHOWN!" )
});
The code from this link worked for me: http://viralpatel.net/blogs/jquery-trigger-custom-event-show-hide-element/
(function ($) {
$.each(['show', 'hide'], function (i, ev) {
var el = $.fn[ev];
$.fn[ev] = function () {
this.trigger(ev);
return el.apply(this, arguments);
};
});
})(jQuery);
$('#foo').on('show', function() {
console.log('#foo is now visible');
});
$('#foo').on('hide', function() {
console.log('#foo is hidden');
});
However the callback function gets called first and then the element is shown/hidden. So if you have some operation related to the same selector and it needs to be done after being shown or hidden, the temporary fix is to add a timeout for few milliseconds.

Categories