Dynamically setting href tag - javascript

On my page there're 2 href links like this:
Name
Phone
The URL that the user is on is based on this format:
http://localhost/site/name/ASDF
I want it so that the website automatically fill out the href boxes like this
Name
Phone
I know I can just assign an id to each of the a tag, and have javascript set the href, but I was wondering if there's a way to do it without having to have a function that sets it once the page is loaded.
Is there a way to do it like I want to? The main problem is the ASDF which is a unique string that the user can specify, so on the page with URL:
http://localhost/site/name/John
the 2 href will be:
Name
Phone

You should get current url then split it and get dynamic name then insert it to href tags. see this exaple:
var fakeUrl = $('#fakeURL').text();
var split = fakeUrl.split('/');
var user = split.pop();
$('#name').attr('href','/site/name/'+user);
$('#phone').attr('href','/site/phone/'+user);
#fakeURL {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="name" href="#">Name</a>
<a id="phone" href="#">Phone</a>
<span id="fakeURL">http://localhost/site/name/ASDF</span>
or another user:
var fakeUrl = $('#fakeURL').text();
var split = fakeUrl.split('/');
var user = split.pop();
$('#name').attr('href','/site/name/'+user);
$('#phone').attr('href','/site/phone/'+user);
#fakeURL {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="name" href="#">Name</a>
<a id="phone" href="#">Phone</a>
<span id="fakeURL">http://localhost/site/name/Jiff</span>
it's an example and will read from fake url you should use this code in your server to get real url:
var url = window.location.href;
var split = url.split('/');
var user = split.pop();
$('#name').attr('href','/site/name/'+user);
$('#phone').attr('href','/site/phone/'+user);
jsFiddle

If your server-side is generating the 's dynamically, you can make it without problem.
If your links are static you need javascript because parts of your href is based on their own properties.
If you use jquery, you dont need to add ids in links in order to fill hrefs, but, If your document is big, the script should be very inefficient.
If you give me more info about your use case, i can help you better.

you can try this..
use query string like localhost/site?name=Max
then do this
$url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].DIRECTORY_SEPARATOR.$_GET['name']

Related

Is it possible to convert a text to URL format using javascript

Basically I want to know that how to build code snippet so that when a user input text and click on the submit button. Automatically add https:// as prefix and .com as suffix and build a valid urls using javascript. And that result should be visible right below the form.
Can anyone help me
Try this out, it take input and covert it to a link by adding https:// and .com
To see it working here just type input as: stackoverflow. If you want to test it with other sites, copy and use the code locally.
function urlMaker(){
var linkVal=document.getElementById("inputText").value;
var href = document.getElementById('aLink').href="https://"+linkVal+".com";
document.getElementById("aLink").innerHTML = href;
}
<input name="inputTxt" type="text" id="inputText">
<button onclick="urlMaker()">Get Link</button>
<br><br>
Mate, I don't know if you know this but not all sites end with ".com" some of them might end with ".edu", ".in", ".io", ".org" etc. Also, some URLs start with "blob:https://" and things like that. I think you probably would need an API.
Yes, it is possible, you just add a keyup or change event listener on the input, and concatenate the text from the input with what you need. Here's an example:
// HTML
<div class="container">
<input type="url" id="url-maker" />
<p class="url-output"></p>
</div>
// JS
const urlInput = document.getElementById('url-maker');
const urlOutput = document.querySelector('.url-output');
urlInput.addEventListener('keyup', (event) => {
let urlText = event.target.value;
if (!urlText.includes('https://')) {
urlText = `https://${urlText}`;
}
if (!urlText.includes('.')) {
urlText = `${urlText}.com`;
}
urlOutput.innerText = urlText;
});
However, you do need to properly validate the strings and also keep in mind that domains end in other extensions than .com! What I've showed you is just a basic example!

Switching to relative location

Hi Wonder if anyone can point me in the right direction.
I'm after some code that I can put on a link that will go to the current page url but in a separate folder or add a language identifier into the url.
So for example, if someone is on FAQ.aspx , they click the Italian link in the menu and it will send them to it-FAQ.aspx or /it/FAQ.aspx and the same for other pages.
Does that make sense? and is it possible, and can someone point me into the direction of where to look
Thanks in advance!
Try something like this :
Get first pathname of the current url, then put language code in front and change href of the link with jquery :
<html>
<a class="switch_language" data-country-code="it" href="">Italian</a>
<a class="switch_language" data-country-code="de" href="">German</a>
and...
<script>
$('.switch_language').each(function() {
$(this).attr('href', $(this).attr('data-country-code') + '/' + location.pathname);
});
Your urls of the language links will be look like this
/it/faq.aspx
/de/faq.aspx
Using a data attribute, you can store the "part to add to the URL" on the link. You can read it using the .data() method.
Then... If you split the actual URL by the /, you can reassemble it and insert the part to be added.
This script will works on any page.
$(".menu .lang").on("click",function(){
// Get the actual page URL
var thisPage = location.href;
console.log(thisPage);
// Split the URL by the "/"
var splitted = thisPage.split("/");
var splittedLength = splitted.length;
// Get the data-lang value
var insert = $(this).data("lang");
// Re-assemble the URL except the last part
var destination="";
for (i=0;i<splittedLength-1;i++){
destination += splitted[i]+"/";
}
// Add the part to "insert" and last part of the URL
destination += insert+"/"+splitted[splittedLength-1];
// OR
// destination += insert+"-"+splitted[splittedLength-1]; // See explanation below the snippet.
// Go to that page!
console.log(destination);
//location.assign(destination); // Commented for this demo...
});
.menu a{
display:block;
text-decoration:underline;
cursor:pointer;
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>FAQ</h1>
<div class="menu">
<a class="lang" data-lang="it">Italiano</a>
<a class="lang" data-lang="en">english</a>
<a class="lang" data-lang-"fr">Français</a>
</div>
Here, the language parameter is added in between / like a it's a directory... But you can easilly add it to the page name like it-FAQ.aspx.

Javascript, change middle part of a link

I have a list of items that are links, and I want to only a part of the link to change based on a input field.
For example:
http://www.myexamplepage.com/?q=%22ITEM1%22&sort=date&from=2017-01-11&to=2017-01-20
So if I want to do this:
<form><input id="date"><input></form>
<a href="http://www.myexamplepage.com/?q=%22ITEM1%22&sort=date&from=XXXXXX&to=XXXXXX">
<a href="http://www.myexamplepage.com/?q=%22ITEM2%22&sort=date&from=XXXXXX&to=XXXXXX">
<a href="http://www.myexamplepage.com/?q=%22ITEM3%22&sort=date&from=XXXXXX&to=XXXXXX">
Where XXXXXX changes depending on the value i input in the input field. Because another part of the link changes (ITEM1, ITEM2, ITEM3 etc.) this solution for example, will not work: How to change part of HTML href elements with javascript all solutions I find are like this one, or they completely changes everything after XXXXXX in the link.
Any tips?
You can cut out the part of the url string using indexOf and subString.
Fiddle example: https://jsfiddle.net/xdckhvyp/
var string = 'http://www.myexamplepage.com/?q=%22ITEM3%22&sort=date&from=XXXXXX&to=2017-01-20';
var startingPoint = string.indexOf('from=') + 5;
var endingPoint = string.indexOf('&to');
string.substring(startingPoint, endingPoint);

Insert current URL into a link using JS and HTML

So, Ive read through similar things but I still can't find an answer that applies more closely to what I'm doing. I am attempting to use JS to get the current page URL and append it to a social media sharing link like this:
<a href="http://reddit.com/submit?url=CURRENTPAGE.html; title="This is a post!" target="_blank">
Using Javascript, I've managed to assign the current URL to a variable:
<script>
var x = window.location.href;
document.getElementById("smsharing").innerHTML = x;
</script></p>
And I made sure it worked by doing a test display of it. So what exactly is the proper method/syntax for actually putting 'x' in place of CURRENTPAGE.html???
I know this is a STUPID question, but I'm really stumped. Specifics help, because part of the problem is that I have precious little knowledge of JS. Thoughts?
This should do it:
<script>
baseurl="http://www.facebook.com?"
function buildURL(item)
{
item.href=baseurl+window.location.href;
return true;
}
</script>
</head>
<body>
<a onclick="return buildURL(this)" href="">Google</a>
</body>
Get the elements current href which doesn't have the url value and append the current url.
Modified HTML
<a id='smsharing'
href="http://reddit.com/submit?url="
title="This is a post!"
target="_blank">link</a>
Script
<script>
var x = window.location.href;
var link = document.getElementById("smsharing"); // store the element
var curHref = link.getAttribute('href'); // get its current href value
link.setAttribute('href', curHref + x);
</script>
Using just pure JavaScript you can set the href of the link by just having the base href as a string and then add the variable where ever it is needed.
var x = window.location.href;
document.getElementById("linkid").href = "http://reddit.com/submit?url="+encodeURIComponent(x);
Using jQuery it is as simple as:
$('a').attr("href",x);
You should simply replace innerHTML by href :
document.getElementById("smsharing").href = x;
Hope this helps.
Once you have access to the current URL, you then want to find the element and replace CURRENTPAGE.html. To do so, you'll need some way to select the element. Let's give it an ID:
<a id="myLink" href="http://reddit.com/submit?url=CURRENTPAGE.html"></a>
Now we can grab the link like so:
var link = document.getElement('myLink');
Let's get the URL again, and give it a better variable name:
var url = window.location.href;
Now let's update the HREF attribute of link:
link.href = link.href.replace('CURRENTPAGE.html', url);
And that's it!
Create another variable for the complete href attribute of your link:
var myURL = "http://reddit.com/submit?url=" + x;
Then replace the current href attribute with that variable:
docment.getElementById("YourLinkTagID").href = myURL

How do I give an ID to part of the contents of a <title> tag?

I have a title tag that looks something like this:
<title>My Page Title - Photo #3</title>
I want to use JavaScript to change the numeric part of it, without having to hard code the "My Page Title - Photo #" string which is generated server side.
I tried wrapping the number in a span so that I could change the contents of the span:
<title>My Page Title - Photo #<span class="photoid">3</span></title>
But it seems HTML is not allowed in the title tag. I'd really like to pursue the class approach if possible as that would allow me to use a line of jquery such as this:
$('.photoid').html(new_photoid);
Did I mention that the photoid appears in several places on the page, which is why I want to be able to use this oneliner to change them all at the same time? For example:
<p>A paragraph also containing the number <span class="photoid">3</span></p>
A title can only have text, so you need to parse it out.
document.title = document.title.replace(/\d+$/, "new value");
title can't be set like that,
it's not a child of .html
some thing like
var num = 3;
document.title = "foo "+num
to set the title, then reuse num for these photoids.
Use the jQuery onDocumentReady syntax:
$(function () {
var elements = $('.contains_photoid');
elements.html(elements.html().replace("3", "4"));
$(document).attr('title', $(document).attr('title').replace("3", "4"));
});
You can't see the title change in this example, but that is the syntax. See Changing the page title with Jquery
The "3" and "4" can be changed to anything, so you can create the page with a unique character string in place of the real ID in order to easily replace it if it appears in text with numbers already in it.
http://jsfiddle.net/ZmXj5/1/
Javascript
var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;
See this fiddle for proof: http://jsfiddle.net/xrkhA/
(I used a div content because you can't use title in jsfiddle)
You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');

Categories