I have a small problem with my links. I am trying to have it so when a link is checked, It uses javascript to handle page loading, This is fine, But before it loads the page I want it to take the URL it passed to JavaScript and check if it is external, If it is, Then alert them, Else just continue... heres the code I have so far:
JavaScript Document:
function loadPage(page, tag, ext) {
if (tag) {
fadeOut(tag);
setTimeout(function() {
if (page) {
console.log('Attempting To Buffer Next Page...');
} else {
console.log('ERROR: No Page To Buffer');
return;
}
if (ext) {
console.log('Loading Custom Extension');
if (checkExternal(page) == true) {
window.location = "external.php?url="+page+"."+ext
}
else {
window.location = page+"."+ext
};
} else {
console.log("No Custom Extension, Using .hmtl");
if (checkExternal(page) == true) {
window.location = "external.php?url="+page+".html"
} else {
window.location = page+".html"
};
}
}, 500);
}
else
{
console.log("ERROR: Tag Field Empty, Cannot Load Page")
};
};
Html Link:
<a onclick="loadPage('https://github.com/hbomb79/securitySystemPro/issues', 'body');" class="url">GitHub</a>
I have tried other results on here, But they all check the href attribute, I need to check a URL passed to a function that returns true if its external.
Anyone got any ideas?
By comparing a click event's .hostname with location.hostname you can easily check if a link is still local.
In the code below I apply a .click event to the class link : Meaning many elements can use the link class to be included in the event handling.
I personally find it preferable to use this method as it requires no changes to the main HTML document. That being said, you could always use onclick="function()" and get the same results.
$(".link").click(
function(e) {
if (e.target.hostname === location.hostname) {
console.log("going local")
return true;
} else if (confirm("Do you with to leave this website?")) {
console.log("Leaving Website");
return true;
} else {
console.log("Staying here");
return false;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class="link" href="http://somewebsite.com"> somewebsite.com </a>
<a class="link" href="#"> # (local) </a>
</body>
</html>
Related
We have a Lottie animation that should act as a preloader and show only on the Home page.
We want to SHOW this when accessing the home page by:
clicking on a link from an external page (not on your website)
clicking refresh on the browser
when entering the URL in the browser's address bar.
We DON'T want to show the animation when
clicking on a link from an internal page (on your website)
navigate through the browser's prev/next history buttons.
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>
<div id="preloader">
<div class="logo" id="home-preloader"></div>
</div>
<style>
/* Some styling here */
</style>
<script>
function playPreloader() {
var animation = bodymovin.loadAnimation({
container: document.getElementById('home-preloader'),
path: 'preloader.json',
renderer: 'svg',
loop: false,
autoplay: true,
name: "Home Preloader",
});
}
</script>
Any ideas on how to do it? I tried a few things with PerformanceNavigation.type and PerformanceNavigationTiming.type but couldn't manage to figure it out. I'm not very skilled in JavaScript, but can manage things if I can have direction.
Even if this worked, it doesn't seem to differentiate between external and internal links.
window.addEventListener("load", function() {
var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
var navigation = performance.getEntriesByType("navigation")[0];
if (navigation.type === "navigate") {
console.log("The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.");
}
else if (navigation.type === "reload") {
console.log("The page was accessed by clicking the Reload button or via the Location.reload() method.");
playPreloader();
yesPreloader();
}
else if (navigation.type === "back_forward") {
console.log("The page was accessed by navigating into the history.");
noPreloader();
}
else {
console.log("Any other way.");
}
});
After researching for two days, I found a comment that was very helpful and helped me create a working solution to my problem. Here's the code for anyone having the same problem.
If somebody can confirm that all of this is correct, that would be nice.
/* (0) WHEN THE PAGE IS LOADED */
window.addEventListener("load", function() {
/* (1) FIND HOW THE PAGE WAS ACCESSED */
var result;
var p;
if (window.performance.navigation) {
result = window.performance.navigation;
// 255
if (result == 255) {
result = 4
}
}
if (window.performance.getEntriesByType("navigation")) {
p = window.performance.getEntriesByType("navigation")[0].type;
// Page was accessed from a link or address bar
if (p == 'navigate') {
result = 0
}
// Page was reloaded (browser reload operation)
if (p == 'reload') {
result = 1
}
// Back or Forward (browser history)
if (p == 'back_forward') {
result = 2
}
// Prerender
if (p == 'prerender') {
result = 3
}
}
console.info(result);
/* (2) WHAT TO DO IN EACH CASE */
if (result == 0) {
// Page was accessed from a link or address bar
console.info("Page was accessed from a link or address bar");
console.info("Result was 0, result=" + result);
// Was it an internal link or (external link or address bar)
if (document.referrer.indexOf(location.hostname) !== -1) {
// Page was accessed from an internal link
console.info("Page was accessed from an internal link");
$(document).ready(function() {
noPreloader();
});
} else {
// Page was NOT accessed from internal link
// Probably accessed from external link or address bar
console.info("Page was NOT accessed from internal link. Probably accessed from an external link or address bar");
$(document).ready(function() {
$(this).scrollTop(0);
document.body.classList.add("overflow-x-hidden");
document.body.classList.add("overflow-y-hidden");
playPreloader();
yesPreloader();
});
}
} else if (result == 1) {
// Page was reloaded (browser reload operation)
console.info("Page was accessed by reloading (browser reload operation)");
console.info("Result was 1, result=" + result);
$(document).ready(function() {
$(this).scrollTop(0);
document.body.classList.add("overflow-x-hidden");
document.body.classList.add("overflow-y-hidden");
playPreloader();
yesPreloader();
});
} else if (result == 2) {
// Back or Forward (browser history)
console.info("Page was accessed from the browser history back or forward buttons");
console.info("Result was 2, result=" + result);
$(document).ready(function() {
noPreloader();
});
} else {
// Any other instance
console.info("Page was accessed: Any other instance (prerender or 255)");
console.info("Result was probably 255 (4) or prerender (3), result=" + result);
$(document).ready(function() {
noPreloader();
});
}
});
/* [END OF] (1) WHEN THE PAGE IS LOADED */
I'm making a plugin for wordpress post page and I'm trying to detect div with id "matched". I can see the div with browser tools, however console throws the message that the div wasn't found. I think that's because script is loading before the page contents. How can I make it to load after the post contents has rendered?
<script type="text/javascript">
var question = document.getElementById("matched");
window.onload = function afterWebPageLoad() {
if(question){
console.log("id 'matched' exists");
} else {
console.log("id 'matched' not found");
}
}
</script>
You were calling document.getElementById before waiting for the page to load with the onload listener.
Move the variable declaration inside the onload listener so that it is only called when the page is loaded.
What your code should look like:
<script type="text/javascript">
window.onload = function afterWebPageLoad() {
var question = document.getElementById("matched"); // <-- Moved inside
if (question) {
console.log("id 'matched' exists");
} else {
console.log("id 'matched' not found");
}
}
</script>
<p id="matched">match element</p>
You can use setInterval like this;
let checker = setInterval(function () {
if (document.getElementById("matched") !== null) {
console.log("found")
clearInterval(checker)
} else {
console.log("checking..")
}
}, 100)
Also, you must check the element in afterWebPageLoad function. You must move question variable to the function.
I have a .cshtml file with the following in the head tag:
<script type="text/javascript">
getPlatform = function() {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
</script>
The reason I've inserted this is because this logic was already taken care of in another javascript file which I've imported in. Essentially what I need to do is change the link of a button depending on which platform the user is using. I've tried the following but this does not work (and even if it did, looks messy and I'm sure incorrect) but I can't seem to find a solution. Can anyone help please?
</div>
getPlatform()</script> id="mobilelink" class="btn"
</div>
One cannot write this:
getPlatform()</script> id="mobilelink" class="btn"
This is how it can be done:
</div>
<a href="" id="mobilelink" class="btn" </a>
</div>
<!-- Later in the page (ideally just before the end </body> tag) -->
<script>
document.getElementById('mobileLink).href = getPlatform()
function getPlatform () {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
</script>
why don't you check it when the page is loaded and change the href of the a tag accordingly? Like:
<a id = "mobileLink" href="">some text</a>
And
var getPlatform = function() {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
document.getElemenyById("mobileLink").href = getPlatform
//Or innerHTML, I don't really understand what you want to do
<script type="text/javascript">
function getPlatform() {
if (Platform.Android) {
document.getElementById('mobileLink').innerhtml = "androidlink";
}
else if (Platform.IOS) {
document.getElementById('mobileLink').innerhtml = "IOSLink";
}
else {
document.getElementById('mobileLink').innerhtml = "other";
}
}
</script>
the html,
</div id="mobilelink" class="btn" onload = "getPlatform()">
</div>
Right now I can only assume the results, that you need. This is one of the ways, inwhich you can return the result from a JS function to the html division. If the onload doesnt work, I'd suggest using an onclick = "getPlatform()" function since that is more aggressive in its notation.
this is incorrect approach.
I would recommend you put all scripts before closer </body> html-tag.
Then in your script you can write such code like:
const platform = getPlatform();
const mobilelinkEl = document.querySelector('#mobilelink');
mobilelinkEl.setAttribute("src", platform);
Make sure, that your script tag with src attribute set placed after script tag with getPlatform, and also make sure you have access to getPlatform function.
If you'll have additional question, write comments, I'll try to help you.
I'm trying to get a string of script to run in an href so the link will redirect users depending on an if/else statement. My code:
<div id="editredirect">
<script>
if("[#authfield:Authentications_2_Region]" == "[#field:Location_2_Region_ID]"){
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else if ("[#authfield:Authentications_2_Region]") == "[#field:Location_2_B_Region_ID]"{
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else {
window.location.href = "member-details?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
</script>
</div>
<style type="text/css">a.ex1:hover {color: #f18c21; text-decoration: underline;}
</style>
<a class="ex1" href="javascript:.initialize(document.getElementById("editredirect"));">Details</a>
I've tred do also do a function like this:
<script>
function editredirect {
if("[#authfield:Authentications_2_Region]" == "[#field:Location_2_Region_ID]"){
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else if ("[#authfield:Authentications_2_Region]") == "[#field:Location_2_B_Region_ID]"{
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else {
window.location.href = "member-details?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
}
</script>
<style type="text/css">a.ex1:hover {color: #f18c21; text-decoration: underline;}
</style>
<a class="ex1" href="javascript:editredirect">Details</a>
Neither one will work. The first string returns a syntax error, the second tells me that "editredirect" is undefined.
Thank you!
EDIT
Praveen Kumar's suggestions were the best. The developer for the database I am using was able to get the application to do it without having to insert any script. However, they did say that the event listener would have also worked once I had my parameters correct.
You can use onclick and add the whole JavaScript logic:
Click me?
The best way is to use event listener like this:
document.getElementsByTagName("a")[0].addEventListener("click", function () {
a = prompt('What\'s your name?');
if (a !== null)
alert('Welcome, ' + a);
else
alert('Bye Bye!');
return false;
}, false);
Click me?
This is better than using href. If you still want to run it in href, you need to create a function and run:
function aha() {
a = prompt('What\'s your name?');
if (a !== null)
alert('Welcome, ' + a);
else
alert('Bye Bye!');
return false;
}
Click me?
Note: In your code, you have used wrong notation. That's a syntax error. JavaScript functions have to be declared in a specific way. Follow that!
I have a link that I am trying to use the history API with - it is on the index page of my single-page-application:
<div id="main">
<div id="logoutlinkdiv">
Log out
</div>
</div>
When I click the link, a template is loaded into the #main div on my index page - and the URL changes to xxx/logout.php as it should. Here is the javascript responsible for the swap:
function supports_history_api() {
return !!(window.history && history.pushState);
}
function swapPage(href) {
var req = new XMLHttpRequest();
req.open("GET",
"templates/" + // ALL MY TEMPLATES ARE IN THIS DIRECTORY
href.split("/").pop(),
false);
req.send(null);
if (req.status == 200) {
document.getElementById("main").innerHTML = req.responseText;
return true;
}
return false;
}
function addClicker(link) {
link.addEventListener("click", function(e) {
e.preventDefault();
if (swapPage(link.href)) {
history.pushState(null, null, link.href);
}
}, true);
}
function setupHistoryClicks() {
addClicker(document.getElementById("logoutlinka"));
}
$(document).ready(function() {
window.onload = function() {
if (!supports_history_api()) { return; }
setupHistoryClicks();
window.setTimeout(function() {
window.addEventListener("popstate", function(e) {
swapPage(location.pathname);
}, false);
}, 1);
}
});
Everything works going forward, but when I click the back button the templates directory gets loaded into the #main div. This happens because location.pathname evaluates to /~Eamon/, and after the href.split("/").pop() - it is just an empty string. Therefore, the templates directory gets loaded because it is the directory pointed to in the swapPage function.
Obviously, all I want the program to do when I click the back button is reverse what just happened. In this case, it would mean swapping back in what I had in the #main div before the link was clicked. How do I "save" what I had before and load it upon clicking the back button? It may be something as simple as changing the directory structure...but I want my application to be an SPA.
Things I have read on the subject:
http://diveintohtml5.info/history.html (this is what I am modeling my code after)
http://www.sitepoint.com/an-overview-and-usage-of-javascript-history-api/
http://html5doctor.com/history-api/
http://dev.opera.com/articles/view/introducing-the-html5-history-api/