Alter URL #ID with JQuery button - javascript

I'm trying to create a function where, on every button click, the ID at the end of the pages URL is added to by 1. So,
example.org/page -> (buttonclick) -> example.org/page#1 -> (buttonclick) -> example.org/page#2 etc. etc.
What I've got at the moment is:
var anchor = 0;
$('#bottom-right').click(function() {
var anchor += 1;
var anchorurl = "#" + anchor;
var currenturl = window.location.href;
var newurl = currenturl.slice(0, -1) + anchorurl;
window.location.replace(newurl);
});
But it doesn't really work & I imagine there is a cleaner solution...
Thanks in advance.

simply make it
$('#bottom-right').click(function() {
window.location.hash = ++anchor;
});
Make use of the built-in hash method.

So basically the url contains #.So you can also track this # and get the next number and increment it.
Code example:
var hashValue = window.location.href.substring(window.location.href.indexOf('#')+1);
window.location.hash = hashValue + 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.

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

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!

Highlight a button based on location

I'm trying to highlight a navigational button (in a menu) based on the page being viewed. Here is what I have so far:
var loca = String(document.location.href);
// Get document location and specific page.
if (loca) {
if(loca.search(RegExp("((/[\w]*)\.php)")) != -1) {
activate(loca.match(RegExp("((/[\w]*)\.php)").split("/").join("")));
} else {
activate("home");
}
}
// Activate a button
function activate(bName) {
$(".button[name=" + bName + "]").css({
"border-left": "1px solid white",
"border-right": "1px solid white"
});
}
What I want to happen is this:
Get URL of page
Get the specific file name of page, and if not found, then we are on the homepage.
Using jQuery, I try to find the name of the button, and if the name matches the filename, then highlight it.
Thing is, this only highlights the "Home" button. What am I doing wrong? Also, if you have any suggestions on how I can better accomplish this, please let me know!
I would get the filename like this, instead:
var pathname = window.location.pathname.split("/");
var filename = pathname[pathname.length-1].split(".")[0];
alert(filename);
Your regular expression is incorrect.
var loc_match = window.location.href.match(/(\w+)\.php/);
activate(loc_match ? loc_match[1] : "home");
I don't have a solution but I would assume the regex is flawed. Did you try to store the result in a variable and console.log it?
I've actually implemented something like this. Here's my code:
var currentPage = window.location.pathname.toLowerCase().split('/').reverse()[0].split('#')[0].split('?')[0];
if (!currentPage || currentPage == '')
{
currentPage = 'default.aspx';
}
$('#nav li').removeClass('current').each(function() {
var href = $(this).find('a').first().attr('href');
if (href && href.toLowerCase().indexOf(currentPage) >= 0)
{
$(this).addClass('current');
}
});
This takes into account any query strings or searches may be in the URL. Using reverse() may not be the most efficient way of doing it, but it certainly works.
When you declare your regexp as new RegExp object, you have to use double backslash escaping symbols (instead one backslash, when you just assign literal like var a = /\w/i; );
So, your code should work after some reg exp correction:
var loca = document.location.href;
var pattern = new RegExp("[\\w]*(?=\\.php)","i");
// Get document location and specific page.
if(pattern.test(loca)) {
activate(pattern.exec(loca));
} else {
activate("home");
}
// Activate a button
function activate(bName) {
$(".button[name=" + bName + "]").addClass('active')
}
And as already said, it's easier to assign class to your active element.

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