Global Javascript link handler - javascript

Here's what I have:
A web application that runs in a single HTML page (call it myapp.req), with content coming and going via AJAX
The application can be entered externally with a link such as myapp.req?id=123, and the application opens a tab with the item at id 123
The content on the page is mostly user's content, and many times has inner-application links to myapp.req?id=123
The problem is that clicking a link to myapp.req?id=123 reloads the browser, and removes any content or state that the user had loaded
What I want is to be able to catch link clicks whose destination is myapp.req?id=123, and instead of reloading the page, just open the tab for item 123, leaving anything else currently loaded alone. If the link is for an external website, though, obviously just let the browser leave.
So my question really: Can I have a global link handler that checks if I want to handle the link click, and if so, run some Javascript and don't leave?
I understand I could find all <a>s and add listeners, but my hope is that the solution would only require setting up the listener once, and not adding link handlers every time new content is loaded on the page. Since content can be loaded many different ways, it would be cumbersome to add code to all those places.
Does that make sense?

jQuery's live is what you need:
$('a').live("click", function () {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
Any link will now have this click handler whether it's been added after this is called or not.

Sure you can. Add a clickhandler on the body. So you catch all clicks. Then you have to check if the target of the event or one of its parent is a link with your specific href. In this case stop the event and open the tab.

updated to use .live instead of .click
If you use jQuery, you can add a "live" click event handler to every a href at once:
<body>
click here
<br/>
whatever
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$('a').live('click',function() {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
</script>
This should extract the id from the href's query string and let you do whatever you want with it.

Related

How do I make a JS function triggered in one HTML page edit elements defined in a second HTML page?

Basically I have two HTML pages, and both are connected to the same JS file. I want a function triggered by an event handler element in the first HTML to edit an element in the second HTML page, and then open it.
Here's a very basic example:
$("#p1").click(function() {
$("#p2el").text("TEST");
})
<button id="p1">CLICK</button>
In this example, the button p1 is defined in the first HTML, and the p2el element is defined in a second HTML page, both linked to the same JS file.
In the above example, I also used location.href inside the function. The idea being that, the element is edited, and automatically the second HTML page is loaded.
It's not working, and I don't know why. The second HTML page loads, but the element p2el is not edited.
I suspect this is has to do with data not transferring to the second HTML, but I am not sure why and what is happening exactly. I tried using localStorage inside the function, and then use the stored data as a condition that edits the element in the second HTML page...
function second() {
if(localStorage["key"] == "on") {
$("#p2el").text("TEST");
location.href = "secondpage.html"
}
}
$("#p1").click(function() {
localStorage["key"] = "on";
second()
})
... but It didn't work.
I hope somebody can help me out.
Navigating to a new page completely resets the "JavaScript envirionment".
Your JS files are reloaded, everything starts anew. Some things persist through page loads, such as local storage and cookies, but function calls certainly don't.
To do what you want to do, you'll need to:
Listen to the click event, and save the fact it was clicked somewhere.
(You're already doing this)
On page load, check the storage to determine whether or not the button was clicked at some time. If it was, do whatever you want. You will probably want to reset the stored value so this happens only once.
This will probably do the trick for you:
if(localStorage["key"] === true) {
localStorage["key"] = false; // reset the key.
$("#p2el").text("TEST");
}
$("#p1").click(function() {
localStorage["key"] = true;
location.href = "secondpage.html"
});

How to run a php file without refreshing the web page?

I have a problem. It is my full honor if anyone helps.
First, let me explain the workflow I want. My CMS is Wordpress. I have a webpage (views.php). In this page, I want to show a download button (id=” download-button”) just to users who has the role subscriber. In default, no one has the role subscriber. So, the button is hidden in default. When a user buys a specific product he gains the role subscriber. Now, suppose a user has opened views.php page as a tab in his browser. In this step, the button is hidden. After that, he opens another tab and buys that specific product and he gains the role subscriber. Now, if he refresh the view.php page, the download button is seen. But, I want the user to see the download button without refreshing the page. In this regard, I wrote button.php file to be called in ajax. However, it does not work.
My codes:
html code (written in view.php which is the place of download button):
<div id="div1"></div>
my javascript code (which is put inside view.php file):
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("button.php");
});
});
</script>
my button.php code:
<?php
if (check_user_role(array('subscriber'))) {
echo ('<button id="download-button">Download</button>');
}
?>
I should note that I have written check_user_role php function in views.php.
It would be my honor if you help.
Thanks in advance.
Milad
As stated by smartdroid in one of the answers above, you can subscribe an event listener function to the window.onfocus event. Try following:
document.addEventListener("DOMContentLoaded", function (event) {
window.onfocus = function () {
$("#div1").load("button.php");
}
});
I highly recomment you to read further into javascript events.
For plain javascript:
https://www.w3schools.com/js/js_events.asp
For jQuery:
https://api.jquery.com/category/events/
Hey you have to use Window setInterval() Method, what this method does it will fire in background at your time interval set.
You can call your ajax code to set/show your button
setInterval(function(){
$("#div1").load("button.php");
}, 3000);
Make sure once you do add this button put return false so it wont execute again and again not to increase load on webpage.
$(document).ready event runs only once after the DOM is loaded. So this event will not fire unless page is reloaded.
If the user is buying a subscription in another browser tab and then returns to the original tab, windows.onfocus event will fire.
So you can use window.onfocus event to check for subscription every time view.php tab becomes active, and then show the button when necessary. So you can use something like the following, in your view.php
$(document).ready(function(){
window.onfocus = function () {
$("#div1").load("button.php");
}
});
Add an iframe to your view.php that doesn't need to contain anyting nor be visible.
<iframe name="download" id="if_download" src="blank.html"></iframe>
Target the download-action to the iframe. With some JS:
function download(href) {
window.frames['download'].location = 'download.php?file=' + href;
return false;
}
You may need to wrap the download-action through a php-file to modify its header
download.php:
$file_name = $_GET['file'];
//validate file exists and *remove any ../ - simple:
if (strpos($file_name, '/') !== false) die('yeah right..');
header("Content-Disposition: attachment;filename=\"$file_name\"");
echo file_get_contents($file_name);
die();

Popstate with Hashtags?

I have a site that uses AJAX to dynamically load content into a div.
The links to do so are anchors with href="#" and an onclick event to trigger the AJAX.
This leaves me without a history when I click back, so if I load one page, then another and click back, it does nothing.
A basic version of the code is this:
<script type="text/javascript">
function loadXMLDoc(url)
{
<!-- Load XML Script here. -->
}
</script>
</head>
<body>
<div id="myDiv">
<!-- Target div. -->
</div>
Click Me.
Click Me.
Click Me.
</body>
What I would like to know is, can I give each link a different "#" and then use a popstate handler to call the appropriate event, so if I click link 1, 2 and then 3 and then start hitting the back button, it'll go back to 2 and then 1 etc..
I was going to use history.js and start using pushstate in the loadXML script but I think the whole manipulating history thing is a bit dirty and unreliable.
Am I thinking on the right lines or is there a better way?
Currently all my links just use "#" so that it pops back to the top of the page when loading more content but I'd like to be able to go back if possible.
Any help would be great.
Browser saves hashtags to history properly. Just add hashtag #1 to this question page, hit enter, change it to #2, hit enter, change it to #3, hit enter. Now click back button, and you'll see hash changes from #3 to #2. I recommend to change only hash itself on link click and react on page hash change and page load events.
function react() {
var hash = window.location.hash.replace("#", "");
loadXMLDoc(hash + ".txt");
};
document.body.onload = function() {
react();
window.onhashchange = react;
};
Click me
Click me
Click me
Please note that onhashchange event does not supported by old IE. The only way to deal with it if you want is to define timer with setInterval and check hashes equality.
Try to use combination of LocalStorage and HistoryAPI.
When you load XMLDoc store it in LocatStorage, when back is pressed - load data from storage, not from web.
A bit code above.
/* Handling history.back added */
window.onpopstate = function(event) {
yourHandleBackFunction(event.state);
};
function yourHandleBackFunction(renderTs) {
/*Check TS and load from localStorage if needed*/
};

"onclick" of a button in a popup works only once

I have an html/php webpage (the file is called searchresults.php) that imports jquery mobile. When you enter the page, the url is usually something like
www.domain.com/searchresults.php?&sort="off"&max="5"
In this example sorting is off and only 5 items are displayed. On that page is a button that opens a popup where I want the user to be able to change these settings. I use the built-in jquery mobile popup. On that popup you can toggle "sort" on/off and you can enter a new maximum. On the popup is an "ok" button to confirm your new settings. It looks like this:
OK
The sortAgain(); function in javascript looks like this:
function sortAgain();
{
//some code to get the necessary variables//
...
//change the href of the button so you reload the page
document.getElementById("okbutton").href = "searchresults.php" + "?keyword=" + var1 + "&sort=" + var2 + "&max=" + var3
}
So, basically, right before the "ok" button navigates to another page, I set its href of the page where it should navigate too.
This scheme works, and the searchresults.php file is fetched again from the server and re-interpreted (with the new variables in the url).
However, if i try to change the settings again after changing it once, the popup just does nothing! In other words, the href of the ok button on the popup stays empty and the javascript function sortAgain() is not called. I don't understand why it calls the onclick method perfectly fine the first time, but then refuses to call it again?
I assume it has something to do with the fact that the popup html code is an integral part of searchresult.php file, and that hrefing to the same page gives problems? The popup is pure html, no php is involved in the popup code. and again, it works fine the first time.
You should check out how to attach events via JavaScript. See here: javascript attaching events
You need to use the "pageinit" event when setting up click handlers in JQM: http://api.jquerymobile.com/category/events/
Here is an example of how to bind click handlers when the page is first loaded.
$( document ).on( "pageinit", "#that-page", function() {
$('#okbutton').on( "click", "#that-page", function( e ) {
$(this).attr("href", "searchreslts.php");
});
});

Javascript : Change the function of the browser's back button

Is there a way to make the user's back button on their browser, call a javascript function instead of going back a page?
You can't override the behaviour that if a user follows a link to your page, clicking Back will take them off it again.
But you can make JavaScript actions on your page add entries into the history as though they were clicks to new pages, and control what happens with Back and Forward in the context of those clicks.
There are JavaScript libraries to help with this, with Really Simple History being a popular example.
yes, you can. Use this js:
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/stealingyourhistory") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://www.programadoresweb.net/");
},0);
}
}, false);
}(window, location));
That will redirect your back button to the location.replace you specify
I think this will do the trick.
you can write your custom code to execute on browser back button click inside onpopstate function.
This works in HTML5.
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
I assume you wish to create a one-page application that doesn't reload the website as the user navigates, and hence you want to negate the back button's native functionality and replace it with your own. This can also be useful in mobile web-apps where using the back button inside apps is common to close an in-app window for example. To achieve this without a library, you need to:
1st. Throughout your application modify the window's location.hash instead of the location.href (which is what tags will do by default). For example, your buttons could fire on click events that modify the location.hash like this:
button.addEventListener('click', function (event) {
// Prevent default behavior on <a> tags
event.preventDefault()
// Update how the application looks like
someFunction()
// Update the page's address without causing a reload
window.location.hash = '#page2'
})
Do this with every button or tag you have that would otherwise redirect to a different page and cause a reload.
2nd. Load this code so that you can run a function every time the page history changes (both back and forward). Instead of the switch that I used in this example, you can use an if and check for other states, even states and variables not related to location.hash. You can also replace any conditional altogether and just run a function every time the history changes.
window.onpopstate = function() {
switch(location.hash) {
case '#home':
backFromHome()
break
case '#login':
backFromLogin()
break
default:
defaultBackAnimation()
}
}
This will work until the user reaches the first page they opened from your website, then it will go back to new tab, or whatever website they were in before. This can't be prevented and the teams that develop browsers are patching hacks that allow this, if a user wants to exit your website by going back, they expect the browser to do that.
If you are creating a one-page web application, where your html body has different sections and you want to nevigate through back button to the previous section you were. This answer will help you.
Where your website sections are differentiated by #. Such as:
your-web-address.com/#section-name
Just follow a few steps:
Add a class and a id in every section in you html body. Here it is ".section"
<section class="section" id="section-name">...</section>
Add two CSS class in your linked css (e.g., style.css) file to your html (e.g., index.html) file such:
.section .hide {
display: none;
}
.section .active{
dislplay: block;
}
Add this JavaScript function in you linked .js (e.g., main.js) file to your html file.
window.onpopstate = function () {
if (location.hash !== "") {
const hash = location.hash;
// Deactivating existing active 'section'
document.querySelector(".section.active").classList.add("hide");
document.querySelector(".section.active").classList.remove("active");
// Activating new 'section'
document.querySelector(hash).classList.add("active");
document.querySelector(hash).classList.remove("hide");
}
}

Categories