How to setup a proper javascript path using path - javascript

I was wondering if anyone can help me correct this code.
I am trying to setup 3 different button menus using var path = window.location.href; for main URL, Russian site and Spanish site.
I seem to have 2 out of 3 working.
I am also sorry if I'm not the best at explaining this but below is what I'm trying to do. Hopefully someone can figure out what I'm doing wrong and help.
var path = window.location.href;
if (~path.indexOf("/ru/")){
$j("#button1").append("<a class=\"ru-text\" href=\"http://#/\"> <span>Отслеживание </span><br/>отгрузки</a>");
}
var path = window.location.href;
if (~path.indexOf("/es/")){
$j("#button1").append("<a class=\"es-text\" href=\"http://#/\"> <span>RASTREAR </span><br/>ENVIO</a>");
}
}else{
$j("#button1").append("<span>Track Your</span> <br/>shipment here");
};
};

You have wrong if-else conditional, it should be as follows:
var path = window.location.href, linkEl = "";
if (~path.indexOf("/ru/")) {
linkEl = "<a class=\"ru-text\" href=\"http://#/\"><span>Отслеживание</span><br/>отгрузки</a>";
} else if (~path.indexOf("/es/")) {
linkEl = "<a class=\"es-text\" href=\"http://#/\"><span>RASTREAR </span><br/>ENVIO</a>";
} else {
linkEl = "<span>Track Your</span><br/>shipment here";
}
$j("#button1").append(linkEl);

Related

Code to change favicon not erroring, but not changing bookmarklet (Jquery)

I am working on a bookmarklet (currently just javascript code) that will prompt the user, asking for a domain name, and whatever domain name they enter will change the favicon of the current site they are on to the one of the domain they entered. I have gotten the code to work without errors, but the favicon doesn't change.
The code does not error, it simply prints "Favicon changed" in the console, but nothing changes.
here is my code:
var script = document.createElement('script');
script.src = '//code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var waitForJQuery = setInterval(function () {
if (typeof $ != 'undefined') {
function changeFavicon(src) {
$('link[rel="shortcut icon"]').attr('href', src);
}
let url;
url = prompt("Please enter the URL you wish to mask this page as. Example: www.google.com", "www.google.com");
changeFavicon("//www.google.com/s2/favicons?domain=" + url);
console.log("Favicon Changed!");
clearInterval(waitForJQuery);
}
}, 10);
Edit: I would like to let it be known I am very inexperienced with javascript, I originally came from Python so I know a bit but a lot of this code may be inefficient or defective. if that is the case feel free to comment or message me about it! Thanks :D
Edit 2: I have tried some other code, this time eliminating jquery.
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
let url;
url = prompt("Please enter the URL you wish to mask this page as. Example: google.com", "google.com");
iconURL = "//www.google.com/s2/favicons?domain=" + url
changeFavicon(iconURL);
It still does not work though.
Consider the following.
$(function() {
function getIcon(url) {
var myData = [
"//www.google.com/s2/favicons?domain=" + url
]
if (url) {
$.get(myData[0], function(results) {
console.log(results);
myData.push(results);
});
}
return myData;
}
$("#get-btn").click(function() {
var newIcon = getIcon($("#url").val());
$("<div>").appendTo($(".prompt"));
$("<img>", {
class: "shortcut icon",
src: newIcon[0]
}).appendTo($(".prompt > div"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="prompt">
<p>Please enter the URL you wish to mask this page as.</p>
<input type="text" id="url" placeholder="www.google.com">
<button id="get-btn">Get FavIcon</button>
</div>
I have found the thing that was wrong!
www.google.com/s2/favicons?domain= does NOT Return an ico file so it failed to work because of so.

Redirect url if checkboxes are selected

I have some problem with redirecting urls after checkboxes are selected. I am using document.location for this, but this doesn´t work in my code. I'm trying to fix it, but without success.
This is the part of my code which doesn't work:
function objednat() {
var adress = "";
if (document.getelementbyid('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adresa;
}
I want to redirect this to a form, which will be filled with the selected values. I don't know why, but this document.location doesn't work in the code.
This is the part of the code I use in the formula for grabbing the hash from the url.
<script type="text/javascript">
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
if (tarifVolani1 == true) {
document.getelementbyid('BoxtarifVolani1").checked = true;}
....
</script>
What am I doing wrong?
Whatever you have done is right, except, the function name is wrong case:
Change getelementbyid to getElementById.
Change adresa to adress.
Code:
function objednat() {
var adress = "";
if (document.getElementById('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adress;
}
jQuery way of doing it
function objednat() {
var adress = "";
if ($('#BoxtarifVolani1').is(':checked')) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/'+adress;
}
For your ref: jQuery :checked Selector

GeoIP Redirect Loop - How to solve it?

I want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages ​​simply edit the following variables:
var defaultsLang are the languages ​​that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();

How to add target = "_blank" in case

I am using Vanilla 2 as forum with buttonbar plugin to create pre tags in the message area.
When clicking on the url button, he generates in the message box, but I would prefer <a href="" target="_blank></a> to generate.
Here is is the .js with the case for the url attribute:
case 'url':
var urlOpts = {};
var thisOpts = $.extend(htmlOpts, {
center: 'href'
});
var hasSelection = $(TextArea).hasSelection();
var NewURL = '';
if (hasSelection !== false) {
NewURL = hasSelection;
delete thisOpts.center;
} else
NewURL = prompt("Enter your URL:",'http://');
urlOpts.href = NewURL;
$(TextArea).insertRoundTag('a',thisOpts,urlOpts);
break;
Can someone tell me how to add the target="_blank" in it?
It seems to be solved so maybe here could be useful for anyone:
I don't know exactly the technologies u are using but have u tried with
urlOpts.target = '_blank';
before
$(TextArea).insertRoundTag('a',thisOpts,urlOpts);

remove first half of string but keep second half in javascript or jquery

I recently created my own personal portal page to replace iGoogle since it's going to be shuttered later this year. Everything is working fine except that one of the RSS feeds that I'm pulling in outputs urls that look like this: http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305
Which when clicked go to a bad url page. How would I remove the first half of that url so that it only has the part starting from the second http://
Strange, but here the link works fine...
Just realized the issue is that somehow the ampersands are being turned into entities which is breaking the links...
Try this. A generic approach.
function queryString(parameter, url) {
var a = document.createElement("a");
a.href = url;
var loc = decodeURIComponent(a.search.substring(1, a.search.length));
var param_value = false;
var params = loc.split("&");
for (var i = 0; i < params.length; i++) {
param_name = params[i].substring(0, params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=') + 1)
}
}
if (param_value) {
return encodeURIComponent(param_value);
}
else {
return "";
//param not found
}
}
var secondHTTP = queryString("url", 'http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305');
var str = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305";
var url = decodeURIComponent(str.split(/https?:/ig).pop());
will result in
"//www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
or
var url = decodeURIComponent(str.match(/^http.+(http.+)/i)[1]);
will result in
"http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
Edit: Code updated, jsFiddle added
HTML:
<input id="schnitzel" type="text" value="http://www.google.com/http://www.real-foo.bar/" />
<input type="button" onclick="$('#schnitzel').val(window.firstHTTP($('#schnitzel').val()));" value="»" />
JavaScript:
window.firstHTTP = function (furl = "") {
var chunked = furl.split("http://");
return (chunked && chunked[2]) ? ("http://" + chunked[2]) : furl;
};
JS-Fiddle:
http://jsfiddle.net/Rm5bU/

Categories