script to replace href http:// with // - javascript

The e-commerce platform I use, bigcommerce, uses global variables to insert data dynamically. I don't have access to the php needed to manipulate the variables server side.
Unless at checkout, the variables all render http: links, I'd like a script to make them relative so if someone wants to browse via https: all of the menu and category links will comply.
I'm currently use this to correct my main nav but it is obviously not a best case solution, and the remainder of the generated links remain http
<script type="text/javascript">
relativeLinking();
function relativeLinking(){
var GLOBAL_PagePath = "%%GLOBAL_PageLink%%".substring(5);
document.getElementById("%%GLOBAL_PageName%%").setAttribute("href", GLOBAL_PagePath);
};
</script>

you can tranform all links using this code:
$(function() {
$('a').each(function() {
var self = $(this);
self.attr('href', self.attr('href').replace(/.*\/\//,'//'));
});
});

Dustin,
This Javascript code
var GLOBAL_PagePath = "%%GLOBAL_PageLink%%".substring(5);
document.getElementById("%%GLOBAL_PageName%%").setAttribute("href", GLOBAL_PagePath);
sets the attributes. Why require this and not just deliver the correct HTML in the first place.
One assumes that needing this that the web master does not know (or care?) the HTML/PHP/JS etc on the two sites (http:// and https:// protocol).
Certain files should be on one site and nor the other. Vice - Versa.

Related

How to keep query string parameters as user navigates through the website

I have a situation where I want to preserve a query string between clicks on my Wordpress website.
E.g.
www.mywebsite.com/?utm_source=mysource
When navigating from this link to another page of the website that query string should persist.
E.g.
www.mywebsite.com/anotherpage/?utm_source=mysource
So I decided one easy way to do this would be to modify the javascript so that my function is fired when a click on an anchor tag occurs.
//Ensures that the query string persists between clicks on the site
$("a").on("click", function (event) {
event.preventDefault();
window.location.href = event.currentTarget.href + window.location.search;
});
However this doesn't work for other elements on the page like buttons which are not anchor tags but still contain hrefs that modifiy the window location when they are clicked. For example in the php scripts of the theme there is code such as:
<button onClick="location.href=www.anotherwebsite.com"</button>
I could implement another function that implements the same behavior for button elements but I am concerned that whenever another element is added I will have to check for a new type. Is there a better way to ensure that whenever the window location is changed my query string persists?
FYI: I am not allowed to put the information in a cookie which is another way I thought of keeping track of the parameters.
several suggestions
client side
In using jquery, it might be easier to just find clickable elements, or have the WordPress theme add css classes, if useful ones aren't there already.
server side
In WordPress, use sessions (but see below), and a rewrite or redirect rule using add_query_arg().
Note about sessions and WordPress: You can't rely on PHP sessions; instead use the database, perhaps via an existing plugin like WP Session Manager or WordPress Native PHP Sessions.
Try this to append query paramters in all anchor tags:-
$('a').each(function() {
var href = $(this).attr('href');
var querystring =
window.location.href.slice(window.location.href.indexOf('?') + 1);
if(href && querystring){
if(querystring.indexOf('=') >= 0)
{
$(this).attr('href', href+'?'+querystring);
}
}
});

Specifying the HTML page that a jQuery selector refers to?

I'm trying to write jQuery code to count the number of <img> elements contained on a site. The site is comprised of 4 separate HTML pages, all in the same folder on the server. Only one of these pages, "pics.html", loads the .js file that needs to perform this function (pics.html is the only page that needs to know how many images are on the site).
It's easy to get the <img> elements from pics.html, since pics.html is the page that loads the script:
var numImgs = $('img').length;
...but I'm confused as to how I would perform this same function in reference to a different page. Is it possible to specify the HTML page that the selector refers to?
I tried this, as a wild guess:
var numImgs = $('test.html:img').length;
Unsurprisingly, it didn't work. I googled for the answer, but couldn't find a solution - or if I did find one, I suppose I didn't understand it well enough to realize that it was the answer.
Thanks for any help you can offer!
To select an object from an external file, you'll need to use $.load().
Reference: http://api.jquery.com/load/
Try this
$(document).ready(function(){
$('#myDiv').load('/remotePage.html #TargetDiv', function () {
var elements = $('.class', this).length;
alert(elements);
});
});

Get Websites Title

I am trying to retrieve the title of a URL for a link.
For example get the title of this:
<a class="stack" href="http://stackoverflow.com" title="Stack Overflow">
will be generated dynamically from something like this: $('.stack').attr("title", "....");.
Is that possible with javascript or jQuery to retrieve the title of a URL?
Thanks alot
Took a little time to make, but this example allows you download a web page from your web page. Then extract the title from the title tags.
<html>
<head>
<!-- jQuery include -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- This include allows cross domain get requests -->
<script type="text/javascript" src="https://raw.github.com/jamespadolsey/jQuery-Plugins/master/cross-domain-ajax/jquery.xdomainajax.js"></script>
<!-- Sample -->
<script type="text/javascript">
$(document).ready(function(){
//gets the href of the first anchor
var url = $("a").first().attr("href");
//sets a get request to get the html source
$.get(url, function(data){
//uses get string between function to get the text between the title tags
//then calls it in a message box
alert(getStringBetween(data.responseText, "<title>", "</title>"));
});
});
function getStringBetween(input, start, end){
var index = input.indexOf(start);
if(index != -1){
index += start.length;
var endIndex = input.indexOf(end, index + 1);
if(endIndex != -1)
return input.substr(index, endIndex - index);
}
return false;
}
</script>
</head>
<body>
Google
</body>
</html>
Yep, just use document.title. Simple and effective.
$('.stack').attr("title", document.title);
EDIT: It looks like I misunderstood your question. If you want to get the title of another page, not the currently loaded page, you could do some cross-domain AJAX trickery, but it's not generally a good idea. I'd just grab the page title server side (in whatever you are using to generate the page [php, asp, etc]) and output it.
For security reasons, you cannot read content from a different website using Javascript, even just to read the title.
You could write a server-side proxy that requests a remote page and finds its <title> tag using an HTML parser.
However, you shouldn't do this at the client side; it will waste time and resources.
If you really want to do this, do it once on the server as a pre-processing step when you create a new page.
Unless the URL's href is on the domain of the current document, using JavaScript to try to get the title of the target document would require cross-domain scripting which is not generally allowed (using traditional methods) by browsers. Unless you're real fancy with proxies (not entirely sure how that is done), you'll need a server-side language to load the document first.

how can I detect page when I compile all javascript to one file

I compile all my javascript for different pages into one file, so I have to identify page for my all.js. I can put a hidden element in my pages and let javascript detect this element, but I don't like this solution, are there any other ways to do this?
You could go by the url using location.href (or another field from the location object).
However, a better approach is using a data- attribute on the body tag, e.g. <body data-page="whatever"> and then using $('body').data('page') to retrieve the value.
If you script is based on pages, then compiling them into one script is a bad idea, load the file separately, it will be lighter and definately increase some performace.
I am not sure, why do you need this, but in general it is not good practice to change dynamicaly change content of javascript file, since you are disabling javascript cacheing, what can be performance issue later.
Any way, you can solve it from other side, what about using all.js just to detect the page, where are you and then you can use this information, to load right javascript file dynamicaly, like in the following example
document.write('<script src="'+location.pathname+'.js"></script>');
Which will load same file as you are on, just with .js extension. So for example on index.html page it will load index.html.js file
I almost always use MVC frameworks and tend to put my action and controller as classes on the body element
<body class="main_controller index">
Which lets you do things like this:
$(document).ready(function(){
//Only for lessons#search
if (!$(body).hasClass('lessons search')) {
return;
}
function close_style_filter_box() {
$('#style_filter_box').slideUp();
}
});
$(document).ready(function(){
//Only for main_controller#index
if (!$(body).hasClass('main_controller index')) {
return;
}
function do_something_else_on_this_age() {
....
}
});
Another way is using javascript variable:
var PAGE = 'page1';

How can I use javascript to convert relative href attributes into absolute paths?

I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site.
Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths...
Right now all of the links are linking to relative paths back to the root.
For example
Home
News
Media
Other
I need a simple way (preferably with jquery) to prepend "http://www.domain.com" to each of those links.
Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ?
$("a").each(function() {
alert(this.href);
$(this).attr("href") = this.href;
});
In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
I don't recommend using javascript to solve this issue. This should be solved in the page template. However, if you still want a jquery solution then here you go. Assuming those links have a specific class that distinguish them from internal links:
$('a.external').each(function() {
$(this).attr('href', domain_name + $(this).attr('href'));
})
you don't need jquery for such a simple function....
var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
var relativeLink = eachLink.href;
var absoluetLink = ["http://",domainName,"relativeLink"];
eachLink.href = absoluteLink.join("");
}
something like this should work, and it runs much faster and you won't need to load the entire jquery library just to run 6 lines of code :P
It's very simple:
$('a').each(function(){$(this).attr('href',this.href);});
When you read the href property of a HTMLAnchorElement, you get the absolute path, so you can overwrite it with attr() method of JQuery.
I noticed that all the solutions here only work with href attributes that begin with a "/" character. If you want something more robust, you may want to try the js-uri library. It looks cool but I haven't tried it myself so I don't know how buggy it is.

Categories