jQuery conditional on the url hash - javascript

In jQuery how can I check if a user is visiting a particular direct id link url?
For example:
http://mydomain.com/#foo
I this case, I like to check for foo.
Would love something like:
if(jQuery.urlHasHash("foo")) {
//logic here
}

No need for jQuery, your browser gives you all you need with document.location.hash
If you want to check if such an ID exists on your page:
var hash = document.location.hash.replace(/^#/, '');
if (document.location.hash != '' && document.getElementById(hash) {
// or just: $(document.location.hash)
// ...
}

Try this Demo http://jsfiddle.net/7QceB/
This might fit your needs :)
Code
$(function(){
//var href = location.href; // get the url
var href = "http://mydomain.com/#foo"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);
});

Try my jsFiddle : jsFiddle here
// it might be from browser & / anywhere else
var url = "http://mydomain.com/#foo";
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
console.log(page); // foo
or just
var url = "http://mydomain.com/#foo";
var page = url.substring(url.lastIndexOf('/') + 1); // #foo
After you can use if statement to know if (page == "foo")

Related

Change button HREF depending on the address bar URL

I have a website that users with an affiliate URL often visit, for example:
https://demowebsite.com/?ref=550
There is a link that initially has an URL:
https://demowebsite.com/register
Register
How can I make that if there is a part with a ref ID in the address bar like https://demowebsite.com/?ref=550, then the href is transformed into the following by click:
https://subdomain.demowebsite.com/ref/
and add the ref ID at the end as an append:
https://subdomain.demowebsite.com/ref/550
And if there is no affiliate part in the address bar, then the link would remain the same.
Register
I would be grateful for any help.
You can use the location object given in tabs
<script>
var href=location.href
if(href.includes('ref')){
document.getElementById('reg')
.href="https://demowebsite.com/ref/" + href.split('=')[1]
}
</script>
Use the URL api
const affRef = (loc) => {
const url = new URL(loc || location.href); // we can pass a url to test
const ref = url.searchParams.get("ref");
if (ref) {
url.pathname += ref;
url.searchParams.delete("ref")
url.hostname = "subdomain."+url.hostname;
}
return url.href
};
document.getElementById("reg1").href = affRef("https://demowebsite.com/register"); // nothing should happen
document.getElementById("reg2").href = affRef("https://demowebsite.com/?ref=550"); // changed
1. Register<br/>
2. Register
On your site you would not need the LOC or pass the URL
const affRef = () => {
const url = new URL(location.href);
const ref = url.searchParams.get("ref");
if (ref) {
url.pathname += ref;
url.searchParams.delete("ref")
url.hostname = "subdomain."+url.hostname;
}
return url.href
};
document.getElementById("reg1").href = affRef();
1. Register<br/>
2. Register
You can change it from the place where the users are being sent. I'm not very sure, but the code would look something like this:
var searchBar; //Assign the Search bar it's value through ID or however you can
if (searchBar=="www.demowebsite.com/register") {
document.getElementById("a").href = ""; //Your desired link
}
else {
document.getElementById("a").href = ""; //Your desired link
}
Register

Receive and send a javascript var

It is solved now
The problem was that I thought getParameterByName() was a defined function, but it is not the case so you need to add this function:
function getParameterByName( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
I hope it helps newbies like me...
I need to receive a variable from the url and, if the user clicks on a button, then send it to another page. To do so, I have got the following code:
html
<input type="button" id="login-button" onclick="factura_si()" value="Yes"/>
Javascript
function factura_si() {
var n = getParameterByName('n');
var string_url = "https://www.webpage.php?" + "&n=" + n;
window.location = string_url;
}
When I use this script, the button does not redirect to the location. Is there something wrong with it?
The function
factura_si() {
var n = getParameterByName('n');
document.write(n);
}
returns nothing... But if I change the parameter 'n' by a random chain of letters 'grniegor', the button shows the chain.
Try setting window.location.href:
window.location.href = string_url;
window.location is an object describing the location of the current page. Setting it's href property causes the page to jump to the new url.
I probe this code and it works, if this does not work for you.
You can check the development tools, maybe the problem is elsewhere.
<input type="button" id="login-button" onclick="factura_si()" value="Yes"/>
the Js functions
function factura_si() {
var n = getParameterByName('n');
var string_url = "https://www.webpage.php?" + "&n=" + n;
window.location = string_url;
}
function getParameterByName(n) {
//call server or somthing...
return "somo_path";
}

ViewerJS str.replace how to make it work

I was taking a look at ViewerJS and seems like a good fit the only problem i found was title came out with %20 instead of space. I know why, but I cannot figure out how to fix it.
so it looks like this code gets worked first. how would i fix it in here to make it display with no %20.
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var x = 'Some%20string%20with%20spaces';
x = x.replace(/%20/g, ' ');
console.log(x);

How to check table for new content, and then update browser tab title?

I am working on a way to flash a browser tab when a new message appears in a table. I have the flashing of the tab part working, my only problem is that I can't seem to get it to flash when a message is received (which is the whole point of my exercise :) )
The newMessage() function is working fine, I just can't seem to get the notification() function to work.
My code is as follows:
function newMessage()
{
var oldTitle = "Your Page";
var msg = "New Message";
var timeout = setInterval(function()
{
document.title = document.title == msg ? '' : msg;
}, 1000);
window.onmousemove = function() {
clearInterval(timeout);
document.title = oldTitle;
window.onmousemove = null;
};
}
function notification()
{
var index = 2;
var content = document.getElementById('refreshMessages').childNodes[index];
var content = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
var knownContent = content.toString();
updater.start();
updater2.start();
var newContent = document.getElementById('refreshMessages').childNodes[index];
var newContent = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
if(knownContent != newContent.toString())
{
newMessage();
knownContent = newContent;
}
else if(knownContent = newContent.toString())
{
alert("No need to flash title.");
}
}
notification();
In the notification() function, I am trying to call the newMessage() function by comparing the strings at the appropiate cell in the table.
I put the alert() into the else if just to see if it would be called, but it does not happen. update.start() and update2.start() are carried out however, as I can see the messages appearing in the table.
I would be happier to use JavaScript but I am open to jQuery also.
My JavaScript is very very rusty so excuse me if I have made any silly mistakes!
Thanks,
Chuck
You have several mistakes in function notification(), see my comments:
function notification()
{
var index = 2;
//Why are you assigning value to "content" for twice?
var content = document.getElementById('refreshMessages').childNodes[index];
/*
* function getElementByTagName is undefined, should be getElementsByTagName,
* 's' is missing. And [1] means the second one not the first one, make sure
* that's exactly what you want.
*/
var content = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
/*
* content is a tr dom object, content.toString() is something like "[object]".
* If you want to get content inside a cell, you should use cell.innerHTML.
* e.g. A table:
* <table id="refreshMessages">
* <tr><td>Hello world</td></tr>
* </table>
* var table = document.getElementById('refreshMessages');
* var firstTr = table.getElementsByTagName("tr")[0];
* var firstTd = firstTr.getElementsByTagName("td")[0];
* alert(firstTd.innerHTML); //alerts "Hello world"
*/
var knownContent = content.toString();
//I doubt these functions really get invoked cuz there's javascript error above.
updater.start();
updater2.start();
//assigning twice, "getElementByTagName" is missing "s"
var newContent = document.getElementById('refreshMessages').childNodes[index];
var newContent = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
//Remove toString(), use innerHTML i metioned above.
if(knownContent != newContent.toString())
{
newMessage();
knownContent = newContent;
}
//You miss an "=" here, to judge a equals b, you should use "=="
else if(knownContent = newContent.toString())
{
alert("No need to flash title.");
}
}

return folders from url

I am looking to write a piece of javascript that will do the following:
Look at current url and return any folders in the url ie:
http://localhost/folder1/page.aspx returns -> /folder1/
http://localhost/page.aspx returns -> /
Any help?
You can try window.location.pathname to get its path. for ref
window.location.pathname.substr(0, window.location.pathname.lastIndexOf("/") + 1);
Via window.location you can access the full URL of your running script. Then you can use a REGEX to extract the part you want, in this case the path.
The location property (on window) (link) has a variety of properties that you can use to get that information.
Here's an example of what's available:
var loc, name, value;
loc = window.location;
for (name in window.location) {
value = loc[name];
if (typeof value != 'function') {
display(name + ": " + value);
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}

Categories