Onclick URL extender - javascript

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!

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.

Overwriting onclick value using jQuery

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/

How do I use page name as textbox value

There's a couple of things I'm trying to achieve with Javascript. I'm a bit of a noob, so bear with me.
Firstly I'm using this code to create a popup window:
HTML:
<img src="request.jpg"/>
JS:
var sPage;
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=400,width=800,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
window.name = sPage;
}
This part works fine, but what I'm then trying to do is take the current page name and put it into the value of a textbox in 'contact.html'.
This is the code I'm using on the popup page to try and do that:
function add(text){
var TheTextBox = document.getElementById("prodcode");
TheTextBox.value = TheTextBox.value + window.name;
}
This seems to work when it's a normal page I'm linking to, but it wont work if it's a popup. I also can't figure out how to get rid of the extension from the page name.
I realise there are probably a million better ways to do this, but this is the one that seems to make most sense to me. I've looked at cookies, but I can't seem to figure them out.
I know I'm asking a lot, but any help would be greatly appreciated.
Thanks.
If I'm understanding the question right, you could pass the window name as a query param in the URL you're passing to your newPopup function, then grab it in the contact.html page to put it into the box.
For example, your newPopup function could add the query parameter to the url like so:
function newPopup(url) {
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
var windowName = sPage.split(".")[0];
popupWindow = window.open(url + '?window_name=' + windowName,'popUpWindow','height=400,width=800,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
window.name = windowName;
}
Then, in your contact.html file, grab the query param when setting the value of your text box, using this sort of logic:
function parseURLParams(name, locat) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(locat);
if (results) {
return results[1] || "";
} else {
return "";
}
}
function add(text) {
var TheTextBox = document.getElementById("prodcode");
TheTextBox.value = TheTextBox.value + parseURLParams("window_name", window.location.href);
}
Hope it helps!

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>

Send variables to javascript(jquery) function

I wont to be able to send a variable to a JavaScript function when I click on a link but for some reason I cant find anywhere on how to do it on the internet.
Here is the function at the top of my page:
<script>
$(document).ready(function(){
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h= &v= ");
});
});
</script>
As you can see I need the variable to be placed after the "h=" and "v=" parts.
Here is the link to activate the function in my page:
<img src="images/map/invisible.png" border="0" />
Variables from where? It's easy enough:
var h = 20;
var v = 40;
$(function() {
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
});
});
Just make sure you escape them with encodeURIComponent().
You can of course get them from anywhere like:
<input type="text" id="txth">
<input type="text" id="txth">
and then:
var h = $("#txth").val();
var v = $("#txtv").val();
Edit: Ok, from your comments I gather you want to send the information from the server back to the client so the client can send it back. The first is to do your click handler in a non-jquery kind of way:
Click me
with:
function handle_click(h, v) {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
}
That's probably the easiest solution. If you want to stick with jquery click handlers you can always embed this information in an attribute or a hidden element. For example:
<div class="special-h">12</div><div class="special-v">34</div>Click me
with CSS:
a.special div { display: none; }
and:
$(function() {
$("a.special").click(function() {
var h = $(this).children("special-h").text();
var v = $(this).children("special-v").text();
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
});
});
There are many variations on this theme.
Lastly, I'll point out that I would advise you not to do attribute lookup selectors where you can possibly avoid it. Give the anchor a class and/or ID and use one of those to assign the event handler. Also use a selector like "a.special" over ".special" too (for performance reasons).
Do you mean appending them into the URL string?
<script>
$(document).ready(function(){
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" + h + "&v=" + v);
});
});
</script>
This assumes you have the variables h and v defined elsewhere in your script.

Categories

Resources