Prevent from running a js file in all the indexed pages - javascript

I'm coding a website with multiple pages (indexed to the index.html) with different content but one header and one footer. The problem is that I linked my footer.js file to all the pages (considering that it needs the same code) but the issue is that it's loading simultaneously when loading multiple pages.
It's a jquery pop-up so when I click to display it in index.html, it's also displayed in contact.html
I don't want to modify my code for every single page, specially because it will be dynamic after.
So here's my javascript :
//open popup
$('.cdv').on('click', function(event){
event.preventDefault();
$('.cd-popup').addClass('is-visible');
});
//close popup
$('.cd-popup').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('.cd-popup') ) {
event.preventDefault();
$(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
$(document).keyup(function(event){
if(event.which=='27'){
$('.cd-popup').removeClass('is-visible');
}
});
//open popup
$('.pdq').on('click', function(event){
event.preventDefault();
$('#cd-popup-politique').addClass('is-visible');
});
//close popup
$('#cd-popup-politique').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('#cd-popup-politique') ) {
event.preventDefault();
$(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
$(document).keyup(function(event){
if(event.which=='27'){
$('#cd-popup-politique').removeClass('is-visible');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can do it in two ways, the first is checking the url pathname and executing code to show a popup only if it meets your criteria
var location = window.location.pathname;
// assume it's an index page
if (location === '/') {
// execute your code to show a popup
}
If your pathname will contain GET attributes, use .indexOf() instead
For this solution you will need to compare pathname to either / or index.html, depending on your server set-up.
Second solution might be a global variable in .html file, for example just before you include your main javascript file.
<script>
window.popup = true;
</script>
And then you can check inside your javascript if this variable has a true value and execute your code.
if (window.popup === true) {
// show popup
}
Documentation: Window.location - mdn

Thank you guys for the help but I think that I solved the problem.
Actually what's causing this bug is Codekit (I use it to compile my SASS files and to minify js files). I can't explain why but when I tried it locally without the software and pushed it to github to see if it works, than it worked.
So if someone can explain it will be great, otherwise for all those who are facing the same problem, just don't care about codekit if you're running it.
Thank you.

Related

Run javascript on website after refreshing

What I would like to achieve is this:
refresh website
run my javascript script on it (just as if I put it in Chrome console).
Question is: how to achieve it?
I can also use PHP for this (set server on my computer that wil be redirecting to the desired website and execute my javascript program on it).
Some example of functionality I want to achieve:
Go to stackoverflow.com -> click StackExchange (you can see it in the top left corner, it can be accessed by a querySelector() in JS) -> refresh stackoverflow.com -> click StackExchange again -> repeat...
If you want to refresh the page behind a DOM element click, you can attach an event handler to the element and then in your event handler execute location.reload() to reload the page.
//When the document has loaded, call the function
document.addEventListener("DOMContentLoaded", function(event) {
if(window.location.hash == "#page"){
console.log("Page reloaded!");
}else{
console.log("Page has a new hit!");
}
});
You can use DOMContentLoaded event listener to solve your problem.
You can do something like this -
var value = localStorage.getItem("logdata");
if(value != null) {
eval(value);
logdata();
}
And try to add logdata to localStorage from console.
Example - localStorage.setItem("logdata", "var logdata = function(e) { console.log('data logged.'); }");
Now when you load the page, logdata function will be called and you can have your code executed.

How to reload div content on click

I have a jQuery script that loads content into a div. When you click on a menu item, the content gets loaded inside of "contentarea" and the URL gets updated. That part works perfectly. However, I would also like to be able to click inside of the div (once content has been loaded into it), and load another page in its place. For example, the Forms page gets loaded into contentarea, and inside of the forms page there is a link to the contact us page. When I click on the link, I would like for the forms page to be cleared from content area and the contact us page to be loaded in its place. See the following image:
With the way my script is setup right now, content only loads when I click from outside of the div.
Here's the code I need to modify:
<script type="text/javascript">
//Jquery loader
function getHash() {
return window.location.hash
}
$("a").on("click", function (e) {
page = this.href.replace("#", "") + ".html",
hash = $(this).prop("hash");
$('#contentarea').load(page, function () {
if (page.match("home.html")) {
history.pushState('', document.title, window.location.pathname);
} else {
location.hash = hash;
};
});
});
//on pageload
history.pushState
var hash = getHash();
if (hash) {
$("a[href='" + hash + "']").trigger("click");
} else {
$("a[href='#home']").trigger("click");
}
</script>
Any help would be greatly appreciated!
Since you are using jQuery, i would propose this:
$(document).ready(function() {
$(document).on( 'click', 'a', function( e ) {
$('#contentarea').load( e.target.href );
});
});
But if you are creating an app, and you are applying it globally, in your case i would reconsider your structure to avoid major changes on your code later. I've passed on that, because you have to manage states (variables of page/state if they exist: like errors, title, url, and obviously content) and determine which of them is active or not to pass to next page or not. Then you have to filter links that you don't want to propague to your history states handler cause you just don't want to...
On some cases, you can't apply existent frameworks on your project because the best approach is to use their code on your framework (yes, create your own framework).
I hope this could help you! :)

Anchor click even not firing after PJAX page load

I am having a pretty strange problem with a website I am messing around with, and I can't wrap my head around what may be going wrong. I am using PJAX on the site, and the have a div in my body with the id of #page-contents.
The code I am using to setup PJAX is as follows...
<script type="text/javascript">
$(function(){
$(document).pjax('a', '#page-contents', {
fragment: '#page-contents',
timeout: 2000
});
});
</script>
I know that the setup is correct because I edited the PJAX file to fire an alert whenever it swapped out the content of my #page-contents div, and I do see that alert when I would expect to (i.e., on link clicks).
I have a navbar along the top (a bootstrap navbar) and I was initially having trouble keeping track of which navbar item would be marked as active. I have solved this problem using the following javascript code.
<script type="text/javascript">
$("a").click(function() {
$(".navbar-nav li").removeClass("active");
var nextPage = $(this).attr("href");
nextPage = nextPage.substring(nextPage.indexOf(window.location.hostname) + window.location.hostname.length);
switch(true) {
case nextPage == "/about":
$("#about-nav").addClass("active");
break;
case nextPage == "/contact":
$("#contact-nav").addClass("active");
break;
case nextPage == "/resume":
$("#resume-nav").addClass("active");
break;
case nextPage.indexOf("/projects") != -1:
$("#projects-nav").addClass("active");
break;
default:
break;
}
});
</script>
This works fine for all links I have in my navbar, but I have found that any links I have inside my #page-contents div will not trigger my above script. I know that PJAX is still working as the page changes and the alert I inserted displays.
A few things I have found in my own testing:
I have also found that if I directly load an address that contains a non-navbar link and then click that link, it will work. But coming back to that page via a pjax reload and then clicking the link will not fire my event.
Adding a test class to one of my anchors and then associating some event with that class has the same problems.
Does anybody know why my script would not be getting executing? Or maybe I am just missing something obvious.
Thank you in advance!
P.S.: The website in question is my personal site I am working on, the link is http://rosshays.me, the page I first noticed this on was my about page. (The site is a work in progress as you'll clearly see.) As mentioned about, going to the about page directly and clicking the link will work, but if you navigate to the about page and then try to click the link in the page, it will not work.
Ross-
I had a similar issue and I know how to solve this; this script is not binding to the new elements because it is not being re-ran on the new elements once they are loaded.
Please put your function in an external .js file. Once complete, you can add this script to your header:
$(document).on('pjax:complete', function() {
$.ajaxSetup({ cache: true});
$.getScript("YOUR SCRIPT FILE PATH HERE', true);?>");
});
You will have to add more $.getScript calls for any other javascript/jQuery that is needed in order to enable the events you want to take place. (Example: you may need to reload jQuery)
This will re-apply the jquery and javascript to the new elements that are loaded via PJAX.
*One thing to note: If you are using twitter bootstrap, do not re-call the bootstrap script with $.getScript as it will cancel itself out on every other re-load.

How to refresh page on back button click?

I use .htaccess to route all of my traffic to a single index.php file. The code below to directs traffic, but for some reason it doesn't work with the back button. I don't know what to do to get the back button working. I've tried a variety of things and googled quite a bit and none of it has worked so I'm hoping someone here can help!
<?php
if(isset($_GET['parameters'])) {
if($_GET['parameters'] == "repair")
include 'repair.html';
else if($_GET['parameters'] == "training")
include 'training.html';
else if($_GET['parameters'] == "products")
include 'products.html';
else if($_GET['parameters'] == "about")
include 'about.html';
else if($_GET['parameters'] == "employees")
include 'employees.html';
else if($_GET['parameters'] == "training")
include 'training.html';
else if($_GET['parameters'] == "newaccount")
include 'newaccount.html';
else if($_GET['parameters'] == "contact")
include 'contact.html';
else if($_GET['parameters'] == "recommended")
include 'recommended.html';
else if($_GET['parameters'] == "careers")
include 'careers.html';
else
include 'home.html';
}
else
include 'home.html';
?>
So far I've tried and failed to use: window.onbeforeunload
body onunload=""
There has got to be a way to onunload=location.reload() or something! Somehow has to know the syntax!!
Try this... not tested. I hope it will work for you.
Make a new php file. You can use the back and forward buttons and the number/timestamp on the page always updates.
<?php
header("Cache-Control: no-store, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo time();
?>
aaaaaaaaaaaaa
Or
found another solution
The onload event should be fired when the user hits the back button. Elements not created via JavaScript will retain their values. I suggest keeping a backup of the data used in dynamically created element within an INPUT TYPE="hidden" set to display:none then onload using the value of the input to rebuild the dynamic elements to the way they were.
<input type="hidden" id="refreshed" value="no">
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no")e.value="yes";
else{e.value="no";location.reload();}
}
A more recent solution is using the The PerformanceNavigation interface:
if(!!window.performance && window.performance.navigation.type === 2)
{
console.log('Reloading');
window.location.reload();
}
Where the value 2 means "The page was accessed by navigating into the history".
View browser support here:
http://caniuse.com/#search=Navigation%20Timing%20API
Reload the site when reached via browsers back button
The hidden input solution wasn't working for me in Safari. The solution below works, and came from here.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
I found two ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1
1. Detect if user is using the back/foreward button, then reload whole page
if (!!window.performance && window.performance.navigation.type === 2) {
// value 2 means "The page was accessed by navigating into the history"
console.log('Reloading');
window.location.reload(); // reload whole page
}
2. reload whole page if page is cached
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
This simple solution posted here Force page refresh on back button worked ...
I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:
<body onunload="">
This disables special cache and forces page reload when user presses
back button. Think twice before you use it. Fact of needing such
solution is a hint your site navigation concept is flawed.
did you try something like this? not tested...
$(document).ready(function(){
$('.ajaxAnchor').on('click', function (event){
event.preventDefault();
var url = $(this).attr('href');
$.get(url, function(data) {
$('section.center').html(data);
var shortened = url.substring(0,url.length - 5);
window.location.hash = shortened;
});
});
});
You can use the following to refresh the page by clicking the back button:
window.addEventListener('popstate', () => {
location.reload();
}, false);
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
<script type="text/javascript">
jQuery(document).ready(function()
{
var d = new Date();
d = d.getTime();
if (jQuery('#reloadValue').val().length === 0)
{
jQuery('#reloadValue').val(d);
jQuery('body').show();
}
else
{
jQuery('#reloadValue').val('');
location.reload();
}
});
window.onbeforeunload = function() { redirect(window.history.back(1)); };
Ahem u_u
As i've stated the back button is for every one of us a pain in some place... that said...
As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this
The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.
But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.

'onbeforeunload' Fires Twice

I want to send an ajax request when a user leaves a page or closes the window.
Here is my code inside :
<script type="text/javascript">
function sendajax(){
$.ajax({
url: "someurl",
data: mydata,
async : false
});
}
</script>
<script type="text/javascript">
window.onbeforeunload=function(){sendajax();};
</script>
When the event occurs the event fires twice.
Why does in happen?
I know I can prevent it by adding a variable var ajaxSent=true; but may be there is a cleaner way to do it?
UPD:
I replaced the sendajax function content with some other code (without sending ajax) and found out that ajax is not the one causing the problem. It still enters the function twice.
Based on the code in your edit and comments, it looks like it could simply be caused by the broken link you are clicking to leave the page.
Given the following code:
<script>
function doSomething() { console.log('onbeforeunload fired'); }
window.onbeforeunload = doSomething;
</script>
link A
link B
If I click on link A, I get two console log entries, if I click on link B I only get one.
It looks like it could be a quirk of how the browsers handle their internal "This web page has not been found" pages, causing your page to be refreshed and closed again before showing the message, leaving you with two occurrences of the onbeforeunload event.
I had the same problem and it took a while to understand and resolve, sharing the case details:
There was a custom JS within our template that manipulated the menu.
It caused the unload to fire twice, only when clicking on the menu links, not on other links, and only in IE/EDGE.
We eventually stopped the propagation on these links and the problem was resolved.
$('.SELECTOR a[href^="http://"]').on('click', function(e){
e.stopPropagation();
});
It's a specific bug in your application, therefore you won't find too much information on google.
You could try the following code:
<script type="text/javascript"><br>
window.onbeforeunload=function sendajax(){<br>
$.ajax({<br>
url: "someurl",<br>
data: mydata,<br>
async : false<br>
});<br>
};<br>
</script>
or you can define sendajax() {} at some place and the use it like onbeforeunload = "sendajax()" not as onbeforeunload = "function () { sendajax() }"
beforeUnload is cancellable
I know this post is quite old but from the Chrome Pagelifecycle API documentation, browsers can occasionally partially unload pages to save resources. https://developers.google.com/web/updates/2018/07/page-lifecycle-api beforeUnload is not reliable to make sure that the page is closed. This especially happens on android devices when the screen is locked.
There is a jsfiddle that I found somebody wrote that you can test out https://jsfiddle.net/ov6b9pdL/. Keep the screen locked for 5-10 minutes on Chrome android and you'll see that beforeUnload is fired without even closing the tab.
$(document).ready(function() {
window.addEventListener('beforeunload', showLoader);
});
var showLoader = function() {
$('#loader').show();
};
Agree with AlonMichaeli's concept.
In my application there was anchor tag wrapped with in a div together with couple of spans. When Anchor was clicked on a dirty page, there was couple of 'Leave site' notifications.
It worked fine if any other part of menuItem (div or spans) are clicked.
So in custom javascript method I've added stopped propagation and preventDefault only if anchor tag is clicked. Somehow in this case preventDefault is necessary.
function menuItemClicked(event: JQueryEventObject) {
var item = $(event.target);
if (item.is(".anchor-item")) {
event.stopPropagation();
event.preventDefault();
}
href = item.closest(".anchor-item").attr("href");
if (!event.ctrlKey && href) {
window.location.href = href;
}
}

Categories

Resources