My site has English and Spanish versions of each page. The folder structure is identical for both, but all Spanish pages are under a /_spanish folder. For example:
/index.htm is English version
/_spanish/index.htm is Spanish version
I'd like to include a button on each page making it easy to swap languages.
The logic is:
onclick parse the full current page name
if it does not contain /_spanish/
insert /_spanish/ and go to that page e.g. go from http://example.com/index.htm to
http://example.com/_spanish/index.htm
else (it does contain /_spanish/)
remove /_spanish and go to that page e.g. go from http://example.com/_spanish/index.htm to http://example.com/index.htm
Thanks in advance for any help.
I've managed to get this working - not the most elegant, but functional.
<button style="width:100px;height:100px;" onclick="myFunction()"></button>
<script>
function myFunction() {
var host = location.hostname;
var path = location.pathname;
var n = path.indexOf('/_spanish');
var len = path.length;
if (n>-1) {
/* make the new page address without _spanish */
var newpath = path.substr(10,len-9);
var newpage = '/'.concat(newpath);
}
else {
/* make the new page address with _spanish inserted*/
var newpath = path.substr(10,len-9);
var spa = "/_spanish/";
var newpages= spa.concat(path);
/*Replace double // that will occur in sub-directories */
newpage = newpages.replace(/\/\//,"/");
}
window.location.href = newpage;
}
</script>
Related
I'm new to javascript & i want to do this simple thing.
I want to make a script which goes to coded url's & clicks on a button each time the script is executed.
Suppose,i have these links -
I want the javascript to to go on these links after running it & trigger another small js for both links after they are fully loaded.
Here's what i tried
var linkArray = ('https://facebook.com/user1','https://facebook.com/user2');
for (var i = 0; i < linkArray.length; i++) { window.open({
url: linkArray[i]
});
}
linkArray.onload="blabla();"
function blabla()
{
var inputs = document.getElementsByClassName('_42ft _4jy0 _63_s _4jy4 _517h _51sy');for(var i=1; i<inputs.length;i++) {inputs[i].click();}
}
Can anyone please help?
Thanks in advance! :-)
Please change to this, this would works
var linkarray = ('https://facebook.com/user1', 'https://facebook.com/user2');
var linkArray = [https://facebook.com/user1,https://facebook.com/user2];
isn't valid, please set your array like this:
var linkArray = ['https://facebook.com/user1', 'https://facebook.com/user2'];
I created a menu in wordpress that both contains anchorlinks to different sections on the startpage, and links to other pages:
But when I navigate to another page (ex "Jobs"), and from there try to navigate in manu to a section on startpage - anchorlinks doesn't work because it needs the full URL to guide user back to startpage and then jump down to the section i clicked. But when I change anchorlinks to full url:
..it will allways reload, even if i'm on startpage because I have the full url. How do i create a menu that will only have section URL (ex "#meetups") on the startpage, and full URL (ex "/hip#meetups") when I'm on another page.
Can I build a javascript or PHP function for this?
I really got stuck here and will be incredibly thankful for any input
I made a jQuery function that will alter menu-link-attr/url depending on browser.location:
var x = location.pathname;
if(x === '/hip/jobs/'){
var findLink = $('.menu-item-type-custom').find('a');
for (var i = 0; i < findLink.size(); i++) {
var attri = findLink.eq(i).attr('href');
findLink.eq(i).attr('href', "http://localhost:3000/hip/" + attri);
}
} else {
console.log('error! ' + x);
}
I have a series of pages named "page-1" "page-2" "page-3" ..."page-99". Is there a way to make a navigation so that whenever I click the "next" button it goes to the next page, and if I click "previous" it will go to the previous page depending on what the current page number is. I was wondering if there is a javascript solution to this since I have never used PHP.
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
This should get you started (starting with your original code).
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
var nav = $(this).attr('data-nav');
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num--;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
Of course, this would be easier:
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
//window.location.href = "page-"+num+'.html'; //The "real" code
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->
And this would be easiest (using the file name):
//className *starts with* nav-
$('[class^=nav-]').click(function(e){
e.preventDefault();
var fileName = location.pathname.split("/").slice(-1);
var fileName = 'http://page-2.html'; //FOR DEMO ONLY
//alert(fileName); //should respond page2.html
var num = fileName.split('-')[1]; //2
var nav = this.className.split('-')[1]; //next
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num = parseInt(num)-1;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->
You can do this with PHP or JS. But in either case you first need to be able to programmatically determine the page number of the currently displayed page.
You mention PHP, is this WordPress or some other similar CMS?
Okay so you mentioned that this is a basic website, but we still need to be able to pull that currentPageID. We could do this a few ways, the coolest would probably be to take it from the url, so let's do that.
To get the number from the url structure you mention in comments (hostname.com/page-1.html):
// Let's first grab the url and pull just the last segment, in case there are numbers anywhere else in the url.
var url = window.location.href;
var array = url.split('/');
var lastSegmentOfUrl = array[array.length-1];
// Next, let's regex that last segment for the first number or group of numbers
var reg = /\d+/;
var currentPageID = lastSegmentOfUrl.match(r); // That's it!
// Then some basic math to get the next and previous page numbers
var previousPageID = currentPageID - 1;
var nextPageID = currentPageID + 1;
// And finally we change the href values on the next and previous <a> elements
document.getElementById('previous').href('/page-' + previousPageID + '.html');
document.getElementById('next').href('/page-' + nextPageID + '.html');
This will keep working forever assuming your url structure stays the same insofar as the last segment only has the current page number and no other numbers, and also that the next and previous anchor tags ID's don't change.
Here is a method using location.pathname and String.prototype.replace, no extra templating required!
Update Includes check that page exists before fetching.
// Check that a resource exists at url; if so, execute callback
function checkResource(url, callback){
var check = new XMLHttpRequest();
check.addEventListener("load", function(e){
if (check.status===200) callback();
});
check.open("HEAD",url);
check.send();
}
// Get next or previous path
function makePath(sign){
// location.pathname gets/sets the browser's current page
return location.pathname.replace(
// Regular expression to extract page number
/(\/page\-)(\d+)/,
function(match, base, num) {
// Function to increment/decrement the page number
return base + (parseInt(num)+sign);
}
);
}
function navigate(path){ location.pathname = path; }
var nextPath = makePath(1), prevPath = makePath(-1);
checkResource(nextPath, function(){
// If resource exists at nextPath, add the click listener
document.getElementById('next')
.addEventListener('click', navigate.bind(null, nextPath));
});
checkResource(prevPath, function(){
// If resource exists at prevPath, add the click listener
document.getElementById('prev')
.addEventListener('click', navigate.bind(null, prevPath));
});
Note that this will increment the "page-n" portion of the path, even if you are in a sub-path. It will also work for non-html extensions.
E.g.,:
mysite.com/page-100/resource => mysite.com/page-101/resource
or
mysite.com/page-100.php => mysite.com/page-101.php
www.baxter.com source page, shows most of the href links starting with the word baxter, like this -
href="/baxter/corporate.page?">About Baxter<
So the way I can construct an absolute url from the above is by combining the base url, www.baxter.com and the relative url /baxter/corporate.page?giving me www.baxter.com/baxter/corporate.page? which results in 404, cause the actual url is www.baxter.com/corporate.page?
I know how to generally parse relative URLs in PHP but is there a way to sense and remove words from relative urls like these?
Also mouseover on About Baxter on www.baxter.com web page displays the correct url, www.baxter.com/corporate.page? at bottom left of the page - where is this coming from? can it be accessed?
Will deeply appreciate any help/pointers...
EDIT on Nov 7:
In main.js, they are removing /baxter:
var fixer = function() {
var init = function() {
var digitasFinder = /(proto)|(cms-)|(teamsite-)/
, baxterFinder = /(\/baxter\/)/
, $allAnchors = $("a")
, $allForms = $("form");
digitasFinder.test(location.host) || ($allAnchors.each(function() {
var $this = $(this)
, actualHref = $this.attr("href");
if (baxterFinder.test(actualHref)) {
var newHref = actualHref.replace(baxterFinder, "/");
$this.attr("href", newHref)
}
}
),
$allForms.each(function() {
var $this = $(this)
, actualAction = $this.attr("action");
if (baxterFinder.test(actualAction)) {
var newAction = actualAction.replace(baxterFinder, "/");
$this.attr("action", newAction)
}
}
))
}
;
return {
init: init
}
}
Looks like some JavaScript executed on page load is modifying the hrefs of the links.
You could try duplicating the effects of the JS code (ie. remove '/baxter' from the links), or for a more generic solution, you could use a headless browser to execute the JS code and then evaluate the resulting DOM. Look into the Mink project for a PHP-based solution.
I have a page that is pulling in a Facebook RSS feed. Unfortunately, the feed contains both relative and absolute paths. I want to give users the ability to click on any given story and read it on Facebook. One of the generated links is relative, so what should be:
http://www.facebook.com/ShannonBaumGraphics/photos/a.253345034707618.56302.102938249748298/805807439461372/?type=1
is converted to
http://www.shannonbaumsigns.com/ShannonBaumGraphics/photos/a.253345034707618.56302.102938249748298/805807439461372/?type=1&relevant_count=1
I tried the following:
<script type="text/javascript">
window.onload = function() {
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace("/ShannonBaumGraphics/photos/","http://www.facebook.com/ShannonBaumGraphics/photos/");
}
};
</script>
But ended up with
http://www.shannonbaumsigns.comhttp//www.facebook.com/ShannonBaumGraphics/photos/a.253345034707618.56302.102938249748298/805807439461372/?type=1&relevant_count=1
I know it's something simple, but I'm not strong enough with Javascript to pinpoint the problem.
you can simply assigning new url.try using this :
aEl.href ="http://www.facebook.com/ShannonBaumGraphics/photos/";
aaEl.href = aEl.href.replace('http://www.shannonbaumsigns.com/ShannonBaumGraphics/photos/','http://www.facebook.com/ShannonBaumGraphics/photos/');
// http://www.facebook.com/ShannonBaumGraphics/photos/a.253345034707618.56302.102938249748298/805807439461372/?type=1&relevant_count=1
Thanks for your help. It pointed me in the right direction. Part of the problem is that the site uses multiple domain names (I should have mentioned that). So I added some PHP to grab the domain name to search for the address, and then replaced it with the Facebook link.
Here's what it looks like now:
<script type="text/javascript">
window.onload = function() {
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace("<?php echo $_SERVER['SERVER_NAME']; ?>/ShannonBaumGraphics/photos/","www.facebook.com/ShannonBaumGraphics/photos/");
}
};
</script>
Maybe there are better approaches, but this seems to work.