JavaScript function fired? - javascript

I'd like to ask somthing that maybe is wrong, but I not sure.
Is there a way to know when a specific function is executed, in order to run a sample of code? I like to make it like an event.
The problem I have is the thick box. I like to resize the thickbox according to the image that display.
To do so, I need to know when the thick box is executed.
Any idea please ?

Thickbox use global function, so you could do below: (As #alex suggested.)
(function($) {
var original = tb_show;
tb_show = function () {
$(document).trigger('tb_show');
return original.apply(this, arguments);
}
})(jQuery);
Then you could bind the event:
$(document).bind('tb_show', function() {
//event handler
});

You could overload the thickbox plugin invocation.
I'm going to assume it is called on a collection with thickbox(), e.g. $('.container img').thickbox().
(function($) {
var original = $.fn.thickbox;
$.fn.thickbox = function() {
// Whatever you need to do here.
return original.apply(this, arguments);
}
})(jQuery);
Now, when you call...
$('.container img').thickbox()
...the code will call your new function before handing the control over to the original function.
You can do whatever you want where it says // Whatever you need to do here. :)

I am not a JS developer but you can create a callback function and make it execute when that specific function is executed.
You can find a good explanation here: JavaScript Callback Scope

Related

Function stored to a variable not running when called

I'm working on a plugin for Trumbowyg where I'm trying to store a function in a variable so it can be called later but also be over-writable without altering the included javascript file.
The problem is, the function is not being called when I try to call it.
Here is my relevant code:
init: function (trumbowyg) {
var plugins = trumbowyg.o.plugins;
...
if(!plugins.giphycrumbs.close_modal) {
plugins.giphycrumbs.close_modal = function() {
console.log('close modal');
$(plugins.giphycrumbs.modal_selector).modal('hide');
}
}
$(document).on('click', '.add_giphy', function() {
trumbowyg.execCmd('insertImage', $(this).attr('src'), false, true);
plugins.giphycrumbs.close_modal;
});
// If the plugin is a button
trumbowyg.addBtnDef('giphycrumbs', {
//this function is handled exactly the same way except it actually works
fn: plugins.giphycrumbs.open_modal
});
}
In my code above, you can see I am checking if plugins.giphycrumbs.close_modal is NOT set, and if thats true, I set it to a function which is supposed to close a modal.
In my click handler for .add_giphy, the insertImage code works, but plugins.giphycrumbs.close_modal is never executed (I don't get the console.log message embedded in the function)
If I do console.log(plugins.giphycrumbs.close_modal) the expected function is put into the console.
Why is the close_modal function not executed in my code?
Answer
Try adding parentheses to close_modal inside your click handler.
Explanation
It seems to me like you are not invoking (calling) this function.
In your click handler, there's this line plugins.giphycrumbs.close_modal;
In javascript, this is a reference to a property on the giphycrumbs object. Though it happens to be a function, it will not be invoked as such unless you use parentheses after it (and optionally give it some arguments).
Hope that helps! 👍

Automatic call of on-click function in jquery

I am looking to call a onclick function forcefully.
$('.checkbox-selector').click(function() {
});
$('.checkbox-selector1').click(function() {
});
When a control goes to the first function, the second function should be called automatically
i.e. onlick event is triggered.
function func1(e) {
// do stuff for selector
// run func2 too!
func2();
}
function func2(e) {
// do stuff for selector1
}
$('.checkbox-selector').click(func1);
$('.checkbox-selector1').click(func2);
Is this what you mean?
If so, make sure to look at the comments! They contain quite valuable information considering events and such.
You can replace func2(); with $('.checkbox-selector1').trigger('click'); to trigger the native event handler too! Using $('.checkbox-selector1').triggerHandler('click'); is practically the same as func2();, whichever you prefer.
Take a look at the jQuery trigger function
Not sure what it is exactly you're looking for, but I'd guess:
$('.checkbox-selector').click(function() {
/* all sorts of stuff*/
$('.checkbox-selector1').click();
//or:
$('.checkbox-selector1').trigger('click');
});
$('.checkbox-selector1').click(function() {
});
Something like that?

Javascript closure behaves differently when bound to an event

I am trying to use a closure to ensure that a function can only execute once. Sounds simple, and it works like this:
function runOnce(fn) // returns copy of fn which can only execute once
{
var ran = false;
return function()
{
if (!ran)
{
fn();
ran = true;
}
};
}
I have tested the function like so:
function lazyLoadGrid(event, ui)
{
alert('hi');
}
var test1 = runOnce(lazyLoadGrid);
var test2 = runOnce(lazyLoadGrid);
test1();
test2();
test1();
test2();
And it works as expected - 'hi' gets alerted exactly twice.
But then I try to use runOnce(lazyLoadGrid) as the callback to a jQuery UI event:
$('.accordion').each(function()
{
$(this).accordion({ autoHeight: false, change: runOnce(lazyLoadGrid) });
});
And madness ensues. What I expect is that each 'accordion' on the page will run lazyLoadGrid() exactly once, when that accordion is first opened. Instead, the closure callbacks seem to behave as if they are all referencing the same copy of 'ran'. lazyLoadGrid() runs the first time I open any accordion, and then never runs again for any other accordion. Logging the pre-condition value of 'ran' shows that it's 'true' every time I click any accordion after the first one.
What is the explanation for this? It may be worth noting I have an odd page, with nested accordions, and multiple jQuery UI tabs each containing accordions. To make matters worse, when I switch tabs the closure actually does run on the first-opened accordion of any given tab. Any advice is much appreciated.
The problem:
I believe the trouble you are having is because what you are thinking of as an "accordion" is actually a "panel". The accordion consists of all the panels in a group. It sounds like you want to run it once per panel, not once per accordion. The following demo illustrates the concept by including two accordions on a page. Notice that lazyLoadGrid() is run twice, once for each accordion:
http://jsfiddle.net/cTz4F/
The solution:
Instead what you want to do is create a custom event and call that event on each panel. Then you can take advantage of jQuery's built-in .one() method which causes that an event handler is called exactly once for each element:
$('.accordion').accordion({
autoHeight: false,
change: function(e, ui) {
ui.newHeader.trigger("activated");
}
});
$('.accordion > h3').one("activated", lazyLoadGrid);
Working demo: http://jsfiddle.net/cTz4F/1/
How about:
function runOnce(fn) {
return function(){
fn();
fn = function(){};
}
}
// test
var foo = function(){
console.log('bar');
}
foo = runOnce(foo);
foo(); // bar
foo();
foo();
i think because the function expects the event parameter to be specified.
try this:
$('.accordion').each(function() {
$(this).accordion({ autoHeight: false, change: runOnce(arguments[0],lazyLoadGrid) });
});
try using directly the function lazyLoadGrid or if you have to use the runOnce you have to specify the arguments[0] (which is the event) as a parameter in the function
-- edit --
sorry i forgot to put the event in the function

Pass function to jQuery .ready() function

I am currently making use of Simon Willson's addLoadEvent function to add functions that I want to run after the load event. I ran into a problem wherein the the function I passed to the addLoadEvent function referenced a div that had not yet been loaded by the DOM and so my action (showing the div) did not do anything. When I changed to using the jQuery $(document).ready function, the div has been loaded by the DOM and I can execute actions with it (make it show up).
So, a couple questions. Why is my function being executed before the DOM has completed loaded using the above function? Is there a way to delay it? The other alternative that I can think of is passing in a function to a jquery equivalent:
function jqueryAddReadyEvent(myFunc)
{
$(document).ready(function()
{
//execute already existing functions
//add a new function to the ready event
myFunc();
}
}
When I try the above code, I get a javascript error "myFunc is not a function". Is there a way to generically pass in a function to the jquery ready function and have it execute? Equivalent to the following:
$(document).ready(function()
{
funcA();
}
$(document).ready(function()
{
funcB();
}
...//more of the same
Replaced with the following:
jQueryAddReadyEvent(funcA);
jQueryAddReadyEvent(funcB);
You can just do:
$(document).ready(myFunc);
to attach functions to the DOM ready event. Here's the fiddle: http://jsfiddle.net/padtE/
If you will require many functions to be added then I suggest you do the following:
Create an array that will old all the functions you want to call.
Add functions to that array as you please.
In the .ready(function() { ... }) call every function in that array.
You're set.
It looks correct to me. Most likely you are calling it with something not a function.
Btw you can shorten this to:
var jqueryAddReadyEvent = $(document).ready
or just use $(document).ready() directly for the same effect, as it specifically does what you want to do, run functions after the load, and is actually shorter.
$(document).ready(funcA);
$(document).ready(funcB);
function jqueryAddReadyEvent(myFunc) {
$(myFunc);
}
jqueryAddReadyEvent(function() {
alert('hello world');
});
Demo: http://jsfiddle.net/AlienWebguy/UzMLE/

Passing jQuery .click() a function as a variable

I'm working with a tabbed interface and have the following jQuery function set up to handle the click events of my tabs.
$(document).ready(function () {
$('a#foo').click(function() {
//content, various calls
return false;
});
});
The above is an example of one of my tabs, the others are also within the same document ready block. What I needed to do was make it so the currently selected tab could not be re-clicked and that in some other cases I could manually disable tabs if needed. I achieved this via the following:
$('a#play').unbind('click');
This works fine, and it certainly disables the tabs but the problem then becomes rebinding the click action that was once there. I achieved this via the bind function:
$('a#foo').bind('click', function() {
//the same content and calls as before
return false;
});
This also works fine, but it has become exceedingly cluttered as I have added tabs to my UI. The immediate solution appears to be to create the function as a variable and then pass it into the initial click creation and into the binding event. Like so:
var Foo = new function() {
//same content and calls as before
return false;
}
$('a#foo').click(Foo());
$('a#foo').bind(Foo());
This, for one reason or another, seems to be causing browser crashing issues. Is it not possible to pass a function as a var in this case or am I just doing it wrong? Alternatively, is there a better way to achieve the results I'm looking for? Thanks.
$('a#foo').click(Foo());
$('a#foo').bind(Foo());
The Foo gives you the function, but adding ()'s after it means you are calling the function instead of passing the function itself. Since you're calling the function, false ends up getting passed to click and bind, obviously not doing anything. Some of your other problems might result from the fact that you simulating switching to that tab twice (calling the event handler twice).
var Foo = function() {
//same content and calls as before
return false;
}
$('a#foo').click(Foo);
$('a#foo').bind(Foo);
^^ should do what you want.
Alternatively, is there a better way to achieve the results I'm looking for?
Currently all we really know about your design is that you are calling using a click event handler to switch tabs. That part is awesome, but we'll need more info to give you the deeper answer you really want. If you post the code inside Foo we should be able to help a bit more. :D
EDIT: credit to SLaks♦ for noticing the new in the function declaration that I missed. I'll add a little more detail to his explanation:
When you write var foo = new
function(...) { ... }, you're making a
function literal, then calling it as a
constructor.
It's equivalent to
var SomeClass = function(...) { ... };
var foo = new SomeClass;
without the SomeClass dummy variable.
The function() {} is an anonymous function as you would expect. new in javascript is a little more confusing. When you call a function and precede it with new, you are using that function to instantiate an instance of a class defined in the function. In JS, unlike most other languages, the entire definition of a class is in one constructor function, from which you set all the instance variables, like so:
Foo = function() {
this.a = "lala";
this.b = 5;
}
To make instance methods of the 'class', you use the prototype attribute. However I just realized I've gotten super off-topic. Read more on that here and here. :D
You need to remove new from the function definition and stop calling the function when using it.
When you write var foo = new function(...) { ... }, you're making a function literal, then calling it as a constructor.
It's equivalent to
var SomeClass = function(...) { ... };
var foo = new SomeClass;
without the SomeClass dummy variable.
You need to simply assign the function literal to the variable.
When you write .click(foo()), you're calling foo, and passing the result to click.
Unless foo returns a function, that's not what you want to do.
You need to pass foo itself by removing the parentheses.
So firstly, click accepts a function, but you call without the () as click runs the function when ready. By adding the () you call it straight up.
Secondly, bind takes a string (what event you are binding to) AND a function (as above)...
Use the following:
function Foo() {
//same content and calls as before
return false;
}
$('a#foo').click(Foo);
$('a#foo').bind('click', Foo);
Hope that helps :)
Try:
var foo = function() // not "new function", as this creates an object!
{
return false;
}
$("a#foo").click(foo); // not "Foo()", as you can't call an object!
As for a better way to achieve the result you're looking for, you could have a class on every tab, such as .tab. That way, you can just do:
$("a.tab").click(function() { return false; });
... without having to fluff around with a lot of ids.
Take a different approach, and do not unbind().
I assume the tabs are all in a common container. If so, just use the delegate()(docs) method to place a handler on the container.
Here's a generic code example:
$('#container').delegate('.tab:not(.selected)', 'click', function() {
$(this).addClass('selected')
.siblings('selected').removeClass('selected');
// rest of the tab code
});
This will only trigger clicks on .tab elements that do not have the .selected class. You'll need to modify for your specific code.
Adding the parenthesis calls the function, but if you wanted to make it cool and stuff, you could make it so that Foo returned the function to be bound.
function Foo(){
return function(){
//your onclick event handler here.
};
}
$('a#bar').bind(Foo())
This makes use of one on javascript's function programming aspects, closures, which is cool, but not as efficient as some of the other answers. You should do some research about closures, as they can be used to make some cool stuff.
http://www.javascriptkit.com/javatutors/closures.shtml

Categories