Append string to every url on page load - javascript

I have my website in English but want to show it in Spanish when page loads. So, I got a script from Google Translate that I put in my header file but I need to append some #googtrans(en|fr) at the end of every URL. What I've done so far is:
$(document).ready(function () {
$('a').each(function () {
this.href += '#googtrans(en|es)';
})
});
But a problem with this code is, it is blocking my popups and bootstrap dropdowns.
Is there any simple way to put that trailing string to every URL on page load.

Filter out links that have attributes or classes you don't want the hash applied to:
For example:
$('a').not('[data-toggle], [href^="#"]').prop('hash','#googtrans(en|es)');
If selectors in not() aren't enough you can use the more robust filter() method
A more ideal approach would be being able to have classes on your <a> to represent the ones you do want modified.
<a class="translate">
$('a.translate').prop('hash','#googtrans(en|es)');
OR
<div class="translate">
<a>
</div>
$('.translate a').prop('hash','#googtrans(en|es)');
Note that using the hash property achieves the same as concatenating href
Without seeing more of your html it is hard to provide a lot more help

Now you replace with this code all <a> tags.
Best way - it's taking Google Translator block links on other div, like this:
<div id="gtr">
...
</div>
And Script:
$(document).ready(function () {
$('#gtr a').each(function () {
$(this).attr('href', $(this).attr('href')+'#googtrans(en|es)');
});
});

Instead of
this.href += “#googtrans(en|es)”;
Try this:
$(this).attr("href", $(this).attr("href") + "#googtrans(en|es)");

Related

How to substitute specific pages? [HTML Multilingual Website]

My question is pretty straight forward.
I have a static HTML website in English.
www.website.com
www.website.com/services
www.website.com/contacts
I also have it translated in German:
www.website.com/de/
www.website.com/de/services
www.website.com/de/contacts
My button (flag) for changing language is located next to my navigation:
<ul class="language">
<li class="de"></li>
</ul>
Option 1: I can just replace the "#" with the German version of the page. For example on www.website.com it is <a href="www.website.com/de/"> and on www.website.com/services it is <a href="www.website.com/de/services">
But this is so much work. Is there an easier way for calling pages by using javascript or .htaccess..or whatever you suggest.
My pages are in .html, so the .php option isn't efficient. And adding "id" to every element in order to translate it.. is even more complicated than the first option.
Thanks in advance!
Ideally, you should probably do that with the server-side language of your website (PHP / ASP / Java / …). If you still want to do it in Javascript, you can do something like that to add /de on front of your current location:
<a href="www.website.com/de/" id="language">
<script>document.getElementById('language').setAttribute('href', '/de'+document.location.pathname);</script>
yep I suspect this javascript should work:
$(document).ready(() => {
let path = window.location.pathname;
if (path.startsWith('/de'))
$('a.lang-switch').attr('href', path.substr(3));
else
$('a.lang-switch').attr('href', '/de' + path);
console.log($('a').attr('href'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="lang-switch">Change Language</a>
Do you have two distinct copies of the HTML? If so, this is probably pretty easy.
Go with your first option, but only for changing languages.
Include a <meta> tag that indicates the current language
Use a javascript event listener to intercept each link clicked and insert the language based on the above meta tag. Something like this;
let lang = document.getElementsByName('lang')[0].getAttribute('lang');
// Get the parent DIV, add click listener...
document.body.addEventListener("click", function(e) {
// e.target was the clicked element
if(e.target && e.target.nodeName == "A") {
e.target.href.replace('yourwebsite.com', `yourwebsite.com/${lang}/`);
}
});
<meta name='lang' lang='de'>
References:
Part of code taken from an answer here

jQuery modifies string that's partial html

I have a problem with replacing links of a string with jQuery. If I pass the string to jQuery, using
$("<div />").html(myContentString))
jQuery strips out all non-closed html tags. If I have an unopened ul-element, and only have the closing in the string, jQuery strips that away.
Any idea on how to iterate over all href attributes of a "partial html string"? I made a quick example which will illustrate this better:
http://jsfiddle.net/yporqgod/
var content = "<li>Option <a href='jadda1'>number 1</a></li><li>Option number <a href='2'>dos</a></li></ul></div>",
$content = $('<div/>').html(content);
console.log($content.html()); /* no </ul> nor </div> */
$content.find("a").each(function() {
var thisHref = $(this).attr('href');
$(this).attr('href', 'exchanged-' + thisHref);
});
console.log($content.html());`
Thanks in advance.
DS.
The reason for having non-closed html tags in a string is that I have to split a bigger chunk of html into three pieces. Don't ask, that's a completely other story ;)
That's just how DOM and jQuery work. The best solution i can give you is to manually add them back when you're done:
console.log($content.html() + '</ul></div>');

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

How to make those dynamic anchor links with jQuery?

I've recently discovered a website which does something really cool! Example:
There are two links "Cat" and "Dog".
There are two DIV containers, id="catImage" and id="dogImage"
The initial URL looks like http://mysite.com/#cat
Initially, the cat image is visible
Clicking on the Dog link will fade out the catImage div and fade in the dogImage div
Additionally, it will change the anchor in the browser URL to: http://mysite.com/#dog
Opening the website with httü://mysite.com/#dog will show the dog image initially
Is this possible using jQuery? How would I scan for that anchor, and how would I call a function when the link is clicked without causing the link to follow some URL? I'm an objective-c dude and don't know anything about JS... hope my question isn't too dumb for you.
with this markup:
<div id="images">
<div id="catImage">some cat image here</div>
<div id="dogImage" style="display:none;">some dog image here</div>
</div>
<div id="anchors">
catImage anchor
dogImage anchor
</div>
and with this js (assuming jquery 1.4.x)
$(function () {
$("#anchors a").click(function () {
// send the index of the anchor to the function
fadeImage($(this).index());
});
var hash = window.location.hash;
if (hash) {
var elementId = "#" + hash.substring(1) + 'Image';
var $div = $(elementId);
// check if this element exists, and if so, send that index to the function
if ($div.length) {
fadeImage($div.index());
}
}
});
function fadeImage(index) {
$("#images div:eq(" + index + ")").fadeIn().siblings().fadeOut();
}
And to explain what's going on here:
I'm using the jquery index() function to get the index of the element relative to its siblings. I then pass that index to the fadeImage function, which finds the same index div and fades it in. By using chaining, I then look to the siblings of that div to fade them out. This is useful if you have more than 2 divs to fade out here.
For the anchor/hash usage, I just find the div with the matching id and get its index, and pass it to the same function.
jQuery docs can explain the various methods much better than I can.
Using location.href you can get the full URL in javascript.
you can substring or string replace your domain name and rest will be your parameter dog or cat.
When you have the parameter .
jquery functions like show(); hide (); to show cat and hide dog.
By adding or removing style also you can change images
.add() is there
addClass removeClass is there
http://mattwhite.me/11tmr.nsf/D6Plinks/MWHE-695L9Z
http://rockmanx.wordpress.com/2008/10/03/get-url-parameters-using-javascript/
http://api.jquery.com/show/
http://api.jquery.com/addClass/
Update: Oh I forgot, obviously you should read a tutorial about jQuery if you want to use it.
You can get and set the hash of the URL via window.location.hash, e.g.
alert(window.location.hash);
//and
window.location.hash = 'test'
You should read about events in order to fully understand how it works. The event object provides a preventDefault() method, which is exactly doing what it says (preventing the default behavior).
E.g. with jQuery:
$('a').click(function(e) {
//Do something..
// prevent to follow the link
e.preventDefault();
});

JQuery Copy text & paste into textarea

I've created a javascript function that will take a hidden span, copy the text within that span and insert it into a single textarea tag on a website. I've written a function in JavaScript that does this (well, kinda, only after a few clicks), but I know there's a better way - any thoughts? The behavior is similar to a Retweet for twitter, but using sections of a post on a blog instead. Oh, and I'm also calling out to jquery in the header.
<script type="text/javascript">
function repost_submit(postID) {
$("#repost-" + postID).click(function(){
$("#cat_post_box").empty();
var str = $("span#repost_msg-" + postID).text();
$("#cat_post_box").text(str);
});
}
</script>
Based on the comment in your question, I am assuming you have something like this in your HTML:
copy post
And I am also assuming that because you are passing a post ID there can be more than one per page.
Part of the beauty of jQuery is that you can do really cool stuff to sets of elements without having to use inline Javascript events. These are considered a bad practice nowadays, as it is best to separate Javascript from your presentation code.
The proper way, then, would be to do something like this:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
And then you can have many more that look similar:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
<a href="#" id='copy-6' class='copy_link'>copy post</a>
<a href="#" id='copy-7' class='copy_link'>copy post</a>
Finally, you can write code with jQuery to do something like this:
$(function() { // wait for the DOM to be ready
$('a.copy_link').click(function() { // whenever a copy link is clicked...
var id = this.id.split('-').pop(); // get the id of the post
var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup
$('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas)
return false;
});
});
This is the best way to do it even if there is only one post in the page. Part of the problem with your code is that on the first click it BINDS the function, and in the subsequent clicks is when it finally gets called. You could go for a quick and dirty fix by changing that around to just be in document.ready.
$("#repost-" + postID).click(function(){
$("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element.
$("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be.
});
And wrap everything in a $(document).ready(function(){ /Insert the code here/ }) so that it will bind to $("#repost-" + postID) button or link when the DOM is loaded.
I had a problem with Paolo's example when I clicked on the link the text that appeared in #cat_post_box was "object Object". Once I added ".text()" to the end of that statement I worked.
var str = $('#repost_msg-' + id).text();
Thanks for you example Paolo!

Categories