Javascript change urls in main menu according to language - javascript

I'm a complete noob on javascript so I would need to know if and how this can be done:
I have a site with 2 languages, English and Italian. The Italian pages are on URL like
www.mysite.com/ita/index.hmtl
while english pages are on
www.mysite.com/eng/index.hmtl
The user changes langages from flag icons.
The problem is, I can't change the menu links separately for ITA and ENG sites, so i can't edit the html directly. So right now when an user goes on the english site, the menu links still point to italian pages.
So is there a javascript code to change ALL urls in the page, so when the user goes to the english version of the site on the page
www.mysite.com/eng/index.hmtl
all urls will be changed from
/ita/
to
/eng/
?

You can use regular expression to change links
var url ='www.mysite.com/eng/index.hmtl', lang = '/ita';
url = url.replace(/\/\w*/,lang);
console.log(url); => www.mysite.com/ita/index.hmtl

Keep language in cookie (jquery cookie plugin) and update all references on page load using default or cookie language.
JS
$("a.changeLang").click(function(e){
e.preventDefault();
$.cookie("lang", $(this).attr("href"));
});
var lang = $.cookie("lang");
$("a").each(function(ref){
$(ref).attr("href", $(ref).attr("href").replace("ita", lang).replace("eng", lang);
});
and HTML
<a class="changeLang" href="ita">ITA</a>
<a class="changeLang" href="eng">ENG</a>

I'm currently using this code:
<script type="text/javascript">
if(document.URL.indexOf("/aprol/") >= 0){
function replace_url(elem, attr) {
var elems = document.getElementsByTagName(elem);
for (var i = 0; i < elems.length; i++)
elems[i][attr] = elems[i][attr].replace('mysite.com/', 'mysite.com/eng/');
}
}
window.onload = function(){
replace_url('a', 'href');
}
</script>
and this as samlple html link
Link
But it works only on firefox, not on chrome or IE9.
Can't understand why honestly.

Related

How to make all website dead links redirect to particular page via JS?

Here's the issue:
Got multiple internal links on the web, still not connected to actual html files.
Im working with local files for the time being
Wanna make js redirect all of the dead links to one particular page (let's call the file: 404-error-page.html) up until I will finish the rest of html files to make those dead links active again
Purpose: wanna keep user away from seeing 404 blank page and instead show em some temporary page (404-error-page.html)
Sorry if that's messy - 1st time adding a question here.
HTML
<html><body><a href="random-link-directing-to-a-non-existing-page"></body></html>
JS
$('a').on('click', function(event) {
var $element = $(event.target);
var link = "404-error-page.html";
if(result.broken) {
if(result.http.response && ![undefined, 500].includes(result.http.response.statusCode)) {
event.preventDefault();
document.location.href = link;
}
}
});
I've already tried some alterations of this code but it's not working for me.
Firstly, need to make this functional on local files and then ofc online.
Any ideas?
Set the data-dead-link attribute to all your unfinished link tag as the follow.
Correct Link
<a data-dead-link>Dead Link</a>
<a data-dead-link>Dead Link</a>
Before the </body> tag insert the follow script
var deadLinks = document.querySelectorAll(`[data-dead-link]`)
deadLinks.forEach(el => {
el.href = "404-error-page.html"
})

Wordpress - Allow older and newer post buttons navigate to a ID

I am looking for a way to modify the below PHP to allow the addition of a ID that once pressed will navigate the user to the start of the blog posts instead of the top of the page.
<div class="post-navigation">
<?php next_posts_link( 'Older Posts', $wp_query ->max_num_pages); ?>
<?php previous_posts_link( 'Newer Posts' ); ?>
</div>
I feel like this is somethign that should be possible without a plugin although I have found a plugin that would allow me to do this piece of functionality.
The intended story would go something like this:
User clicks on 'older' or 'newer' button that would have in the url something like domainName.co.uk/page/2#startofposts
The user then would have the browser refresh and instead of the page being loaded at the top it would be loaded where the ID 'startofposts' would be in the DOM.
Anyone done this without a plugin?
Cheers
jQuery(document).ready(function() {
var startID = '#post-container';
var urlString = window.location;
var caseSearch = '/page/'
if(urlString.indexOf(caseSearch) != -1 {
jQuery(window).scrollTop(jQuery(startID).offset().top);
}
}
this should do the trick. There are better ways to do this but for a quick solution id should be fine.
In the end I appended the wanted ID onto the end of the anchors manually.. preventing me from having to do anything too fancy.
$('.post-navigation a').each(function () {
var current = $(this);
var href = current.attr("href");
current.attr("href", href + '#post-container');
});

Business Catalyst Web Apps cannot use jQuery on the Page

I created a Web App for NavBar and located it on my template. It is working fine.
{module_webapps,28592,a,,,,false,20,false,1}
And this is the code for this WebApp:
<li>
<a id="{tag_href-id}" href="{tag_href-id}">{tag_title}</a>
</li>
Then, for showing the active page as highlighted, I coded this jQuery in my template:
window.onload = function(){
var url = window.location.pathname;
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var filename = "#" + filenameWithExtension.split(".")[0];
$(filename).addClass('active');
};
The idea is adding class="active" inside of a tag; if its id equal to last part of the URL.
I used the same idea before, without WebApps. I wonder that, is there any limitation about using jQuery in a page, to change something about an element which comes from Web Apps? Could it be related page`s loading order. Or am I missing another thing?

Javascript substring method assistance

So long story short im working on a web app and using AJAX within it.
I'm trying to disable the default actions of links when clicked, attach a hash value to the link and then remove the "#" from the url.
the problem im having is that, although the hash values are being attached accordingly, the substring method isnt extracting the "#", it extracts the letter after it.....
here is my code. PS, i left my comments inthere so you get where im trying to go with this
so i dont know....my logic or setup may be wrong....
$(document).ready(function(){
//app vars
var mainHash = "index";
var menuBtn = $('.leftButton');
//~~~~~~load the index page at first go.
loadPage();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~menu show/hide
menuBtn.click( function(){
$('#menu').toggleClass();
});
//Menu items on click , disable link default actions.
$('#menu a').click( hijackLinks );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~functions for mobile index load AND hijacking app links to AJAX links.
function loadPage(url){
if( url == undefined){
$('#contentHere').load('index.html #content', hijackLinks);
window.location.hash = mainHash;
} else {
$('#contentHere').load(url + '#content', hijackLinks );
}
}
function hijackLinks(e){
var url = e.target.href;
e.preventDefault();
loadPage(e.target.href);
window.location.hash = $(this).attr("href").substring(1);
}
});
what im wanting is to remove the "#" from the url. What am i doing wrong, what am i not seeing/understanding?
ive tried substring/substr etc and both do the same thing in that no matter what numbers i choose to insert into the substrings params, they remove EVERYTHING BUT the "#" lol....
Thanks in advanced.
Well, you don't really change the link itself, you only change the window.location.hash, and the hash always has a "#" at the beginning.
What you need to do in order to change the entire url (and remove the '#') is to manipulate the browser history.
Although you should know it works only in newer browsers (the exact browser versions are in the link), so if you target your website to older too browsers you might need to think about having a fallback using the hash. If you decide to have such a fallback, I suggest searching for a plugin which does it instead of making it all yourself.

How to make a link open multiple pages when clicked

I have two (or more) links. For example: http://google.com and http://yahoo.com.
How can I make them both open when I click on a single link?
For example, a link entitled "click here" which, when clicked, will open two different blank windows.
HTML:
Click Here
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('http://yoururl1.com');
window.open('http://yoururl2.com');
});
window.open also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.
Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.
I did it in a simple way:
<a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>
It'll open runningrss in a new window and virtual-doctor in same window.
You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:
HTML
<ul class="yourlinks">
<li><a href="http://www.google.com/"></li>
<li><a href="http://www.yahoo.com/"></li>
</ul>
jQuery
$(function() { // On DOM content ready...
var urls = [];
$('.yourlinks a').each(function() {
urls.push(this.href); // Store the URLs from the links...
});
var multilink = $('Click here'); // Create a new link...
multilink.click(function() {
for (var i in urls) {
window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
}
});
$('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});
This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)
You can open multiple windows on single click... Try this..
<a href="http://--"
onclick=" window.open('http://--','','width=700,height=700');
window.open('http://--','','width=700,height=500'); ..// add more"
>Click Here</a>`
You need to unblock the pop up windows for your browser and the code could work.
chrome://settings/contentExceptions#popups
I created a bit of a hybrid approach between Paul & Adam's approach:
The link that opens the array of links is already in the html. The jquery just creates the array of links and opens each one when the "open-all" button is clicked:
HTML:
<ul class="links">
<li></li>
<li></li>
</ul>
<a id="open-all" href="#">OPEN ALL</a>
JQUERY:
$(function() { // On DOM content ready...
var hrefs = [];
$('.links a').each(function() {
hrefs.push(this.href); // Store the URLs from the links...
});
$('#open-all').click(function() {
for (var i in hrefs) {
window.open(hrefs[i]); // ...that opens each stored link in its own window when clicked...
}
});
});
You can check it out here:
https://jsfiddle.net/daveaseeman/vonob51n/1/
Here is a basic implementation in javascript - I separated it into an external file
HTML
Click To Open Links
JS
var myLinks = [
"https://google.com",
"https://www.w3schools.com/jsref/met_win_open.asp",
"https://developer.mozilla.org/en-US/docs/Web/API/Window/open"
]
function openMultipleLinks(links) {
for (var i = 0; i < links.length; i ++) {
window.open(links[i]);
}
}
Note that the user will have to enable pop-ups for the pages to open.
Here it is in action: https://jsfiddle.net/cuppajoeman/rjavuhcg/
If you prefer to inform the visitor which links will be opened, you can use a JS function reading links from an html element. You can even let the visitor write/modify the links as seen below:
<script type="text/javascript">
function open_all_links() {
var x = document.getElementById('my_urls').value.split('\n');
for (var i = 0; i < x.length; i++)
if (x[i].indexOf('.') > 0)
if (x[i].indexOf('://') < 0)
window.open('http://' + x[i]);
else
window.open(x[i]);
}
</script>
<form method="post" name="input" action="">
<textarea id="my_urls" rows="4" placeholder="enter links in each row..."></textarea>
<input value="open all now" type="button" onclick="open_all_links();">
</form>

Categories