How can I get two onClick calls to fire? - javascript

Firstly I am not a web developer, I'm an Analytics professional, so I apologise if this question seems basic and not using the correct terminology!...
I am trying to get _trackEvent code to fire 'onClick' for some Social buttons - however as the social buttons open in a new window they already run an onClick as follows....
I need to add in the following _trackEvent code:
onClick=_gaq.push(['_trackEvent', 'EN', 'Tower of London', 'Facebook']);
So what I am trying to do is fire an event to Google Analytics on click whilst not disturbing the button functionality. Any help is much appreciated

Just put the tracking command before the window open command in the onClick
like this:

A quick JavaScript/HTML lesson : what the contents of the inline "onclick"-attribute describe is the body of a "callback" function (a method that, in this case, is executed when the element is clicked). In this case it opens the Facebook share URL in a new window/tab when the anchor is clicked.
What you want to do is execute TWO different callbacks for the single click-event. This would lead us to using JavaScript to assign the event callbacks using "addEventListener/attachEvent" as the inline "onclick"-attribute only allows for a single callback handler, while adding listeners gives you the benefit of being able to add multiple callbacks for a single event type. As others have mentioned, if you have jQuery or another library available this can be a doddle to attach.
However, if you want a quick and dirty fix without getting too much JavaScript code going on outside of your HTML document, you can add the _gaq-tracking code inside the "onclick"-attribute by appending after the existing onclick-code like so:
Which will result in tracking the click in Analytics AND the window openeing. Semantically, this is quite fugly as it describes multiple handlers in a single of code, but for the sake of argument we assume you don't mind as the HTML had inline JS handling to begin with and we haven't even touched the subject of window opens being blocked when they are delegated through multiple functions instead of on a direct-click handler! ;)

Instead of using onclick, attach the events using jquery if you have it:
<script type="text/javascript">
$('.facebook').on('click', function () {
window.open('http://www.facebook.com/share.php?u=http://www.londonpass.com/infographic/hampton-court.html&title=Hampton Court - History and Stories Infographic from the London Pass/','newWin','width=400,height=200')
_gaq.push(['_trackEvent', 'EN', 'Tower of London', 'Facebook']);
//other code you like
});
</script>
For attaching the event using pure javascript:
var socials = document.getElementByClass("facebook");
socials.addEventListener('click', myFunction, false);
And define your function:
<script type="text/javascript">
function myFunction () {
window.open('http://www.facebook.com/share.php?u=http://www.londonpass.com/infographic/hampton-court.html&title=Hampton Court - History and Stories Infographic from the London Pass/','newWin','width=400,height=200')
_gaq.push(['_trackEvent', 'EN', 'Tower of London', 'Facebook']);
//other code you like
}
</script>

Related

Attaching an event listener for left or right click - onclick doesn't work for right click

I am currently applying for an Internship Internship Link
One of the things that I noticed right away is that you click on upload cover letter or paste cover letter, you're redirected to the home page of the job invite site Job Invite and sadly you can't upload your cover letter. On the other hand, the upload resume works perfectly fine but paste resume has the same issue.
Does anyone know how to resolve this issue and and be able to submit a cover letter?
I am not a web guru but since I am applying for an engineering position, I am trying to find a way around this. I right clicked the upload cover letter link and inspected the link with the inspect element tool. I found that this function
onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')
was going to get called when the button is clicked. Now going into the JavaScript file for this html page, Inspect Element -> Sources -> *careers_8.js?v=303, I tried to do a basic alert statement, from alert dialog, to do some debugging to see what the issue is. Here's the code now
function jvAddAttachment2(id, companyId){
alert("I got here");
....
}
I then did control s and the Inspect Element console outputted "Recompilation and update succeeded." so I am assuming the JavaScript file has been updated. However when I click the link(via right click, open new window), no alert box shows up. Does anyone know how to get the alert dialog to show up? I think I've done as much as I can with my working knowledge from one web development course haha.
You're looking for the contextmenu event for right click:
element.addEventListener('contextmenu', function() {
// code here
});
Please don't use inline js, like onclick in your html. The above sample is the proper way to attach event listeners.
You should get your element reference in javascript with var myElem = document.getElementById('the-id') or some similar function like document.querySelector, etc.
Then, you can easily attach both events like this:
// left click
myElem.addEventListener('click', myFn);
// right click
myElem.addEventListener('contextmenu', myFn);
If you're adamant to do this with inline js, that would be:
<div onclick="myFn()" oncontextmenu="myFn()"></div>
Full demo of both approaches for ya:
var myElem = document.getElementById('my-element');
myElem.addEventListener('click', myClickFn);
myElem.addEventListener('contextmenu', myClickFn);
function myClickFn() {
console.log('this is myClickFn!');
}
function someFn() {
console.log('this is someFn!');
}
<div id="my-element" onclick="someFn()" oncontextmenu="someFn()">Left or Right click me!</div>
Also, since you're wanting to pass parameters to the function you'll be calling on click, it is good to use an intermediary function for the event, and have that function call the other function, passing the parameters, like this:
function myClickFn() { // this is called on click
myOtherFunction('some', 'params');
}
That prevents you having to repeat the same function call, passing those same parameters in both places.
Make sure to close your onclick string at the end with a ":
onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')"
And left click instead of right clicking.
onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')"
I think that double quotation was absent.
demo

Completely delete all instances of a div with a specific class using javascript/jquery?

I am using Popup.js by Toddish.
http://docs.toddish.co.uk/popup/demos/
Long story short, the popup plugin creates divs by default given the classes ".popup_back" and ".popup_cont".
I have another button I wish to press which should completely delete the added divs with those classes after they have been generated and added to the html. As if they never even existed. Surely this is possible?
I have tried running a function which simply runs:
$(".popup_back").remove();
$(".popup_cont").remove();
As shown in this example:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_remove
Unfortunately despite the code running, the actual divs are never deleted as required.
Any ideas? I am new to this kind of thing and have googled around and read a lot about DOM etc but am yet to crack it.
Thanks
EDIT:
In reply to the comments:
The Javascript:
function removePopups() { // This function is called to remove the popups.
console.log("removing...");
$(".popup_back").remove();
$(".popup_cont").remove();
}
function func(url) { // url is the url of the image to be displayed within the popup.
removePopups(); // As soon as the function casillas is called, removePopups is used to remove any existing instances of the divs.
$('a.theimage').popup({ // This is where the Popup plugin is utilised.
content : $(url),
type : 'html'
});
}
The HTML:
<a class="theimage" onclick="func('image/image1.jpg')" href="#" >
Long story short, an image is displayed in the popup.
I think the issue is that the popup plugin runs due to the class but the function func is never actually run when the click occurs. However simultaneously "removing..." still prints out in the console which tells me that the function IS being executed. The problem is I want the popup plugin to run together with the javascript function. Is there a solution for this conflict?
Your implementation should really be as simple as this:
<a class="theimage" href="#" >Open</a>
Bind the popup creation to your popup link:
$('a.theimage').popup({
content : 'image/image1.jpg',
type : 'html'
});
I'm speculating here, but what might be happening is that you're invoking the popup twice by binding the popup() call to a click handler in your markup. The popup plugin already binds the popup creation to a click event.
View working demo. Note the 3 external resource: the popup CSS, the popup JS, and the jQuery JS.

Check if the webpage has been modified

I am working on chrome extension for facebook. If you use facebook, you know that when you scroll down to the bottom of the news feed/timeline/profile it shows more posts. The extension actually adds a button beside the "like" button. So I need to check if there are more posts to add that button to.
Right now to check if the page has been modified, I use setInterval(function(){},2000).
I want to run a function when the user clicks the button. But this function doesn't work if I put it outside (or even inside) setInterval() – The Koder just now edit
How can I check if the webpage has been modified WITHOUT using a loop?
Example:
$(document).ready(function(){
window.setInterval(function(){
$(".UIActionLinks").find(".dot").css('display','none');
$(".UIActionLinks").find(".taheles_link").css('display','none');
$(".miniActionList").find(".dot").css('display','none');
$(".miniActionList").find(".taheles_link").css('display','none');
//only this function doesn't work:
$(".taheles_link").click(function(){
$(".taheles_default_message").hide();
$(".taheles_saving_message").show();
});
//end
$(".like_link").after('<span class="dot"> · </span><button class="taheles_link stat_elem as_link" title="תגיד תכל´ס" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{"tn":">","type":22}"><span class="taheles_default_message">תכל´ס</span><span class="taheles_saving_message">לא תכלס</span></button>');
$(".taheles_saving_message").hide();
}, 2000);
});
In the future, this extension will use AJAX, so setInterval() can make even more problems for me.
If I understand correctly you want to get a notification when the page's DOM changes. And you want to do this without using the setInterval() function.
As your problem lies within the attaching event handlers to elements that are created after the page has loaded, you might be interested in checking out the jquery.live event attachment technique. I think it will solve your issue.
In general you want the page to throw a mutation event. There is a mutation event spec that might be what you're looking for. Here are some links that might be useful.
http://tobiasz123.wordpress.com/2009/01/19/utilizing-mutation-events-for-automatic-and-persistent-event-attaching/
Detect element content changes with jQuery
$(document).ready(function(){
setInterval('fun()',5000);
fun();
});
function fun()
{
alert(11)
}

How do I discover which function is called when I press a button?

I'm stuck modifying someone else's source code, and unfortunately it's very strongly NOT documented.
I'm trying to figure out which function is called when I press a button as part of an effort to trace the current bug to it's source, and I"m having no luck. From what I can tell, the function is dynamically added to the button after it's generated. As a result, there's no onlick="" for me to examine, and I can't find anything else in my debug panel that helps.
While I prefer Chrome, I'm more than willing to boot up in a different browser if I have to.
In Chrome, type the following in your URL bar after the page has been fully loaded (don't forget to change the button class):
var b = document.getElementsByClassName("ButtonClass"); alert(b[0].onclick);
or you can try (make the appropriate changes for the correct button id):
var b = document.getElementById("ButtonID"); alert(b.onclick);
This should alert the function name/code snippet in a message box.
After having the function name or the code snippet you just gotta perform a seach through the .js files for the snippet/function name.
Hope it helps!
Open page with your browser's JavaScript debugger open
Click "Break all" or equivalent
Click button you wish to investigate (may require some finesse if mouseovering page elements causes events to be fired. If timeouts or intervals occur in the page, they may get in the way, too.)
Inspect the buttons markup and look at its class / id. Use that class or id and search the JavaScript, it's quite likely that the previous developer has done something like
document.getElementById('someId').onclick = someFunction...;
or
document.getElementById('someId').addEventListener("click", doSomething, false);
You can add a trace variable to each function. Use console.log() to view the trace results.
Like so:
function blah(trace) {
console.log('blah called from: '+trace);
}
(to view the results, you have to open the developer console)

Calling Javascript function from XPCOM, C++

My goal is to catch pageloads in my component, insert some javascript into the document and then catch onFocus events. On an event i then want to call the javascript function i injected.
Now i managed to solve most issues, i have the script added to all webpages and i can catch onfocus events. What im not able to do is execute a javascript function from my XPCOM component (C++). In my Internet Explorer BHO i use execScript and it works great. Any ideas?
Currently my workaround is to use setattribute and set the onfocus event of each input element to execute the javascript function, but this is intrusive and overwrites existing onFocus handlers in the webpage. Other ideas are welcome.
Thanks.
If you "have the script added to all webpages", the script can take care of both registering a "focus" event listener and taking an appropriate action when the focus event happens.
I'm not sure why you need to call into the content JS from your component.
If you do need to do this, post what you have already tried and in what way it "didn't work".
I believe this used to resolve your issue (pre FF6?), am looking for a newer solution.
FF6 had some change to security of the navigation bar that prevented executing javascript there. https://support.mozilla.org/en-US/questions/876916
Where to execute java script the url might be javascript:alert('hello');
OnStateChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRUint32 aStateFlags, nsresult aStatus) {
// check for correct state - document load complete...
nsCOMPtr<nsIDOMWindow> domWin;
nsresult rv = aWebProgress->GetDOMWindow(getter_AddRefs(domWin));
nsCOMPtr<nsIWebNavigation> nav = do_GetInterface(domWin);
if (nav)
hr = nav->LoadURI(url, 0, 0, 0, 0);

Categories