Overwriting onclick value using jQuery - javascript

I'm attempting to create a function that will select all anchor tags with both http and _gaq (because a lot of the links have event tracking on them), and then add Google Analytics cross-domain tracking linker method to the onclick event:
$("a[href*='http:'][onclick*='_gaq']").each(function(){
var href = this.href;
var onclick = $(this).attr('onclick');
var linker = "['_link', "+ "'"+href+"'"+"],";
var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');
console.log('output : '+output);
});
When I run this, it outputs:
output : _gaq.push(['_link', 'http://google.com'],['_trackEvent','dude','dude','dude']); return false;
This is what I'd like the new value for onclick to be, so I'm wondering how can I have the output value 'overwrite' the old onclick value?
I've also created a jsfiddle to illustrate.
Appreciate any help or suggestions.

Try
$("a[href*='http:'][onclick*='_gaq']").each(function(e){
var href = this.href;
var onclick = $(this).attr('onclick');
var linker = "['_link', "+ "'"+href+"'"+"],";
var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');
$(this).attr('onclick', output);
});

I found this question which probably gets you the answer you want:
$("a[href*='http:'][onclick*='_gaq']").each(function(){
var href = this.href;
var onclick = $(this).attr('onclick');
var linker = "['_link', "+ "'"+href+"'"+"],";
var output = [onclick.substr(0,10), linker, onclick.substr(10), " return false;"].join('');
$(this).attr('onclick','').unbind('click'); // Get rid of the old one
var f = new Function(output); // create a function
$(this).click(f); // Add your new onclick
});
Edit: I was Led astray by a more recent comment with 26 upvotes. Switching back to my original form.
26 votes Yet it doesn't seem to work!, compare
http://jsfiddle.net/TN2wr/
with
http://jsfiddle.net/TN2wr/1/

Related

passing actual URL parameters to a button

I'm working on a web funnel , that i would like to track starting from step number #1 .
I'm trying to pass URL parameter for example :
https://mywebsite.com/###/######.html?subid=160445&eng_source=160445&eng_subid=null&eng_click=1d1ba0f6784b4c36918f087b616a3366
i want to pass the "subid=#" to the next destination which is button link
so it becomes:
https://landing.mywebsite.com/2scstep.html?subid=160445
or what ever "subid" was there before .
i just need some instruction from where to start adding this or what language should i work with .
Thanks A lot .
OK, lets imaging you have button on the page, which is
<a id="button" href="https://landing.mywebsite.com/2scstep.html">
Take me to new destination
</a>
If I understood you question correctly, you want change the destiantion of the button (href) so it becomes oldhref + '?subid=#'
It can be done in many techniques in javascript. Simpliest way is to install jquery, and then make smething like this
//Wait untill whole document is loaded
$(document).ready(function(){
//You now is on the page, that has url e.g. `href` + `?subid=12345`
// you got to get you subid var to javascript
//Get whole url
var currentHref = window.location.href;
//Get only params part, by splitting string by ? and taking second part
var currentHrefParamsPart = currentHref.split("?")[1];
//Now get all params to array (there can be lots of params)
var paramsArray = currentHrefParamsPart.split("&");
//Now get subid value
var subid = false; //its not known yet
paramsArray.each(function(params){
var key = params.split('=')[0]
if (key == "subid") {
var subid = params.split('=')[1]; //We got it
}
})
//Now you gotta change href attribute of the button if subid was found
if (subid) {
var $button = $("#button");
var oldHref = $button.attr("href"); //get the old href
var newHref = oldHref + "?subid=" + subid; //make new href
$button.attr("href", newHref);
}
})
It is not working code, there could be mistakes or tyopos, I wrote it to give you an idea how to achieve the result, what techiques and languages should be used.

jscript to run at window.onload AND item.onchange

I'm using jscript to load a string in to several elements of an array, then display the useful element in html.
There's a pulldown menu that causes the string to change. So, I need the function to be re-run when that happens.
I have been able to successfully display the element using window.onload
and, I have been able to successfully display the element AFTER the pulldown menu has been changed.
But, I can't seem to display the element with window.onload and subsequently after item.onchage
If anyone has any suggestions, I'd be grateful.
Here is the code that works for window.onload
window.onload = function() {
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
//loads the string in to an array and returns the 2nd element
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
}
Here is the code that works for pulldown.onchange
jQuery(function(){
jQuery('.dropdownimage-format select').on('change', function(){
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
});
In both cases, the element is displayed in html by
<a id="MASNUM">

Onclick URL extender

My problem resides within the syntax of the onclick funtion.
My URL for the page I'm working on(Simplified for obvious reasons):
www.mytestsite.com/tier-1/tier-2.html
My code right now:
<div onclick="location.href='tier-3.html';">
When clicked, it attempts to bring me to a page with a URL of:
www.mytestsite.com/tier-1/tier-3.html
I'd like it to extend the current URL dynamically so it'll bring me to:
www.mytestsite.com/tier-1/tier-2/tier-3.html
Does anyone know if this is possible to do within the onclick function? This is going to be dynamic, so I'm reluctant to do the simple fix of:
<div onclick="location.href='tier-2/tier-3.html';">
I really appreciate any help anyone offers me!
You should not use inline javascript, it's hard to debug to debug and keep things scoped. Just create an event listeners for each div.
You can set a topdir variable, that you change to suit your needs.
//pure javascript way:
var topdir = "tear2/";
document.getElementById('mydiv').addEventListener("click", function(){
window.location = topdir + "tier-3.html";
});
document.getElementById('mydiv2').addEventListener("click", function(){
window.location = topdir + "someotherurl.html";
});
//jquery way:
var topdir = "tear2/";
$('#mydiv').on('click', function(){
window.location = topdir + "tier-3.html";
})
$('#mydiv2').on('click', function(){
window.location = topdir + "someotherurl.html";
})
Try this:
document.getElementById("yourdiv").setAttribute("onclick", "location.href='tier-2/tier-3.html';");
EDIT
Use global js variables if you wanna increase your "tier" value and extend your url.
Your html:
<div onclick="url_update();"></div>
Then create your global var and your function:
var global_url = "tier-1";
var global_count = 1;
function url_update(){
global_count++; // increase "tier" value
global_url = global_url + "/tier-" + global_count;
// your new global_url will be = "tier-1/tier-2";
location.href = global_url + ".html";
}
I hope it was what you were looking for!

How to dynamically create list of <a> tags using js

I am creating html page which needs to create a list of links dynamically on a click of button. I know how to create this list when number of links to be created is known before like this:
//For 4 tags:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.innerHTML = "link1 text";
aTag.setAttribute('onclick',"func()");
mydiv.appendChild(aTag);
var bTag = document.createElement('b');
bTag.innerHTML = "link2 text";
bTag.setAttribute('onclick',"func()");
mydiv.appendChild(bTag);
var cTag = document.createElement('c');
cTag.innerHTML = "link3 text";
cTag.setAttribute('onclick',"func()");
mydiv.appendChild(cTag);
var dTag = document.createElement('d');
dTag.setAttribute('onclick',"func()");
dTag.innerHTML = "link4 text";
mydiv.appendChild(dTag);
But the problem is that the count will be known at run time and also on function call i need to identify the id of link that invoked function.. Can anybody help?
I don't know weather you receive or not the HTML to be shown in the anchor, but anyway, this should do the work:
function createAnchor(id, somethingElse) {
var anchor = document.createElement('a');
anchor.innerHTML = "link" + id + " text";
anchor.setAttribute("onclick", "func()");
return anchor;
}
Then you call the function like this:
function main(num_anchors) {
var mydiv = document.getElementById("myDiv");
for (var i = 0; i < num_anchors; i += 1) {
mydiv.appendChild(createAnchor(i));
}
}
Of course this code can be improved, but this is just for show how can this be possible.
Yes it is possible to do this at runtime .
JQuery provides very useful dom manipulation . So you can traverse the dom , filter what you need ..
you can find a lot of useful functions here .
http://api.jquery.com/category/traversing/
It would look something like this.
$( document ).ready(function() {
$( "a" ).each(function( index ) {
// enter code here..
}
});
document.ready gets invoked once the DOM has loaded.

How can I change the href of an anchor after it has been clicked?

I have a page that pulls in data via AJAX. As well as this I have a link to download said data as a CSV file.
The problem I have is that upon I need to pass some parameters along with the click event so that the server can return the correct CSV file.
Without any processing the link looks like this:
Download Target Reports
This then fires off an ASP.NET MVC Controller action that returns the CSV. What I want to do though is pass two parameters along in the query string. Initially I thought that I could intercept the click event and add data to the query string like so:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
It would seem that changing the href at this stage will not update the link in time and the URL will be as it was when it hits the server?
Is it possible to change a URL after it has been clicked or do I need to look at another method?
Thanks
You could redirect the window yourself, like this:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
window.location.href = this.href + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
return false; //prevent default going-to-href behavior
Or, whatever is updating those hidden fields, update the link then instead of when it's clicked, for example:
$("#someField").change(function() {
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
$("a.black").attr("href", function() {
return "/manager/TargetResults.csv" + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
});
});
The main difference is this still allows normal click behavior to work, ctrl+click, etc.
Just rounding out your options, you could put a span inside the link:
<span>Download Target Reports</span>
...and then hook the click event on the span, which will happen before the click on the link.
you can make javascript redirect here:-
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
location.href=link;
ya someone can disable js but your code is completely based on js.
Thanks
Without having a href, the click will reload the current page, so you need something like this:
jhhghj
Or prevent the scroll like this:
jhhghj
Or return false in your f1 function and:
jhhghj
....or, the unobtrusive way:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php"; `enter code here`
return false;
};
</script>

Categories

Resources