Execute function via jQuery - javascript

On my site I have a number of links to various external booking forms that should open in new windows. Unfortunately I can only change each links class (can't set the Id's).
What I'm trying to do is to come up with a Javascript that has a function for each external site to open in a new window. And some jQuery that executes the proper function for the link clicked with a certain class in it.
This is one of the functions (others have a different name and url):
function booking-site-1(elt) {
window.open("https://bookings.domainname.eu/4043/31", "_blank", "toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745");
}
And this is the jQuery
jQuery(".booking-site-1-class").click(function(){
alert("Finally!")});
Where the jQuery now successfully shows the alert when I click a link I'd like it to execute the function shown above. I such a n00b that I don't know how to do that.
Hope that someone could give me a few pointers here.

Firstly, function names declared using var/const/let/function can't have hyphens - - in fact, no names declared as such in JavaScript can. Use underscores instead:
function booking_site_1(elt) {
window.open("https://bookings.domainname.eu/4043/31", "_blank", "toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745");
}
And to make it execute, just add it to your click handling function:
jQuery(".booking-site-1-class").click(function(){
alert("Finally!");
booking_site_1($("#randomElement"));
});
As pointed out by Jaromanda X in the comments, you can make functions as a property of the window object, or of any object,

Related

Basic JQuery syntax: What mechnaic is at work in this small (2 line) piece of JavaScript / JQuery

So here' s the piece of code. I'm very new to JavaScript so don't be afraid to explain the obvious
$(".my-css-class").on("click", function() {
($(this).attr("data-property-1"), $(this).attr("data-property-2"), this);
});
There's an element in the .jsp page that looks like this:
<i class="clickMe"></i>
I know the .jsp creates a link-icon, and that the above JavaScript is an event handler. I know that it passes these 3 values as arguments another JavaScript method:
function doStuff(prop1, prop2, obj) {
if (prop1 == 'foo') {
//do stuff with prop2
}
else{
// do stuff with obj
}
}
It all works fine. What I want to know is what exactly is going on to make it work? I can't find anything in the code that connects what the event-handler returns to the 'doStuff' java-script function.
The names are totally different, so it's not reflection, it can't be parameter matching because there's other functions with the same number and type of parameters in the file, it can't be convention based because it still works if I find/replace the name of the function to gibberish.
I guess basically I'm asking what this line is doing:
($(this).attr("data-property-1"), $(this).attr("data-property-2"), this);
tl;dr: I'm at a loss, I know how the properties get as far as the onClick event-handler's anonymous function - but how does JavaScript know to pass them as arguments the to the doStuff() function?
the onClick event is a standard event triggered on click of any clickable html element and is automatically raised by the DOM.
You are hooking in to this by listening on any matched ".my-css-class" elements for an onClick Event.
The jquery syntax ".on" has been simplified over time and allows you to hook into any number of events like "submit" - OnSubmit event , or "load" - onLoad Event
Wherever your on("click", myFunction) event hook is picked up, your myFunction will execute.
Looking at your second point...
because it still works if I find/replace the name of the function to gibberish.
The DoStuff function will be found and replaced across all files in your site? or page? or open tabs? , so therefore it must exist somewhere as "doStuff(" or "giberish(".
so when you do a global find/replace, do each one slowly, until you locate it.
Finally, when you do a view source in the browser, this should either explicitly show you the doStuff function, or at the very least give you a clue as to satelite files loaded at runtime, where you can go and investigate.
Use firebug in firefox to debug loaded resources; the ".net tab" to view external loaded resources and the html/javascript they might contain. (for example: your master page might be loading in an embeded resource that contains the doStuff method, becuase of a user or server control reference in that master page)
Also have a look at this:
http://www.developerfusion.com/article/139949/debugging-javascript-with-firebug/
You can step through the javascipt piece by peice until it hits the doStuff method.
Just remember to set at least 1 breakpoint ;-)

Way to access anonymous objects' methods

There is a website, which uses this code below to create website functionality:
$(document).ready(function(){
{
function I_WANT_TO_ACCESS_THIS_METHOD(){
CODE HERE
},
SOME OTHER CODE
}
});
I want to update this website with a greasemokey script, but I don't want to duplicate code already written. That's why I want to access methods that are part of such objects (in the code above it is the I_WANT_TO_ACCESS_THIS_METHOD()).
I'm not a JS master and I'm not sure if it is even possible, but I think that this is the right place to ask ;)
I_WANT_TO_ACCESS_THIS_METHOD() is not a method of an object, but just a function defined inside another function. So you can't access it outside that function(the domcument ready callback function) scope.

Create Multiple Instances Of Same Script

I am currently building a website that uses windows to load in new content via ajax. These windows are allowed to contain the same page as in another window using the same javascript. Currently I assign a unique id to the new window which it then stores for later use.
Once the code is loaded in, all the ids in that window are converted by adding on to them a unique_id. ie "box" becomes "box_win1". I then send this id to the javascript by assigning it to a variable so it can be used in document.ready function.
The pseudo code for the window is like the following:
document.ready{
var temp_id=id+1;
$("#mybox" + temp_id).val("abc")
//run some startup stuff
}
I am just wondering is there a better way to do this. As I find if I open to many new windows all at once the temp_id conflicts and goes to the wrong window.
I would like to some how create an instance of the code but I am not sure how. I cannot use global functions however as that may cause naming conflicts.
put this into a function
function callMe (){
var temp_id=id+1;
$("#mybox" + temp_id).val("abc")
//run some startup stuff
}
you can use callMe() anywhere then

How can I use jQuery 1.5.2+ on a Firefox addon?

At first I made a function that received a parameter and returned jQuery such as:
function getjQuery(window)
{
/*jquery code*/(window);
return window.jQuery;
}
But then I got an email form the review and they told me I have to use jQuery file with the original file name and completely unmodified.
I started to search for an alternative and found this solution, but there is no way it work.
jQuery object is created, but I can't find any elements. $("#id").length is always 0. With the previous method it was always found.
My current code (which doesn't work)
AddonNameSpace.jQueryAux = jQuery;
AddonNameSpace.$ = function(selector,context) {
return // correct window
new AddonNameSpace.jQueryAux.fn.init(selector,context||contentWindow);
};
AddonNameSpace.$.fn =
AddonNameSpace.$.prototype = AddonNameSpace.jQueryAux.fn;
AddonNameSpace.jQuery = AddonNameSpace.$;
The jQuery file is loading on my browser.xul overlay:
<script type="text/javascript" src="chrome://addon/content/bin/jquery-1.5.2.min.js" />
Am I loading in the right place?
How can I use jQuery to modify the content on a page (HTML) with the original jQuery file, is it even possible?
You need pass the e.originalTarget.defaultView on the second parameter on jquery..
If you don't jquery will use window.document, which is the window.document from the xul.
Use
gBrowser.addEventListener("DOMContentLoaded", function (e) {
$("#id", e.originalTarget.defaultView).length
}, true);
instead of
$("#id").length;
And, for avoid conflicts with other extensions don't use script in the xul page, use MozIJSSubScriptLoader.
Components.classes["#mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader)
.loadSubScript("chrome://youraddon/content/jquery-1.5.2.min.js");
If you use this method, you load jquery only when you need, avoiding memory leak.
The preferred way to load it is with mozIJSSubScriptLoader so you don't collide with other's extensions. I'm not sure why you're having problems, I can use jQuery in my addon like $("#id").hide() with no additional code (although from the sidebar, now browser.xul).
Either way, this blog post provides a pretty good guide and even has an example xpi to download.

How can I discover what JavaScript function is called when clicking on something on a page?

I'm trying to deconstruct part of Gmail and can't seem to be able to find what is happening (what functions are called) when a specific button is clicked.
I used Google Chrome's inspector and found the HTML for the button:
<tbody id=":8y" class="vC " idlink="" role="option" aria-labelledby=":8x :8w"><tr class="vI"><td><img class="vt SFzvCe IRnhDe BUw1sf" id=":8x" src="images/cleardot.gif" alt="Call phone"></td><td id=":8v" class="vr" colspan="2"><span id=":8w" class="HHshnc ">Call phone</span></td></tr></tbody>
In the "Event Listeners" section of the inspector under "click" I got this information:
isAttribute: false
lineNumber: 213
listenerBody: function B(H){return g.call(B.src,B.key,H)}
node: tbody#:8y
sourceName: https://mail.google.com/mail/u/0/?ui=2&view=js&name=main,tlist&ver=q0qiADndhKA.en.&am=!k3sV9...
type: click
useCapture: true
but that doesn't help me understand what's being called onClick.
What I'm trying to do is create a Greasemonkey script that will add this button to Gmail when it doesn't exist on a page.
TIA!
function B(H){return g.call(B.src,B.key,H)}
is clearly only a wrapper function that calls g. Function.call
[c]alls a function with a given this value and arguments provided individually.
As you can read on the linked MDC page, the first argument is the this object inside g, in this case B.src. The second and third parameter are passed as parameters to g.
So, you'll have to look for a function named g. The toString method might be helpful.
That said, given the goal you're trying to reach (“create a Greasemonkey script that will add this button to Gmail when it doesn't exist on a page”), I think it's not worth your time. If the button doesn't exist, I suspect it doesn't exist for a reason (e.g., g not being available on that page, or some other back-end function).

Categories