Execute JavaScript function with externally loaded link - javascript

I'll admit the title is a bit confusing but it was hard to come up with a better one.
Ok, so What I have is 3 pages, first is the main page that the user loads up and the other 2 are ones that are going to be loaded into the main page with jQuery.
Here is the JavaScript code on the first page:
$(document).ready(function(){
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php");
$('[name=loadRegisterForm]').click(function() {
$("#mainWrap").load("modules/web/registerForm.php");
});
});
First of all it loads the login form into the page and then it listens for a link to be pressed which will then load up the register form in its place if it is pressed.
The link is in the login form that gets loaded, but unfortunately it doesn't work. What am I doing wrong?
I've tried placing the link on the main page with the JavaScript code and it does work, so is it just the fact that loading the link after the JavaScript has all ready been loaded going to leave it not working?

You need to have a callback function for the first load call. In side that call back is where you would set the click handler for the $('[name=loadRegisterForm]') element. Basically,
you are binding a handler to an element that does not exist until the first load is complete.
$(document).ready(function(){
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php", null, onLoadComplete);
});
function onLoadComplete()
{
$('[name=loadRegisterForm]').click(function() {
$("#mainWrap").load("modules/web/registerForm.php");
});
}

Related

functions with button.click() are not executing the click part

I have 2 function as below:
<script type="text/javascript">
sm=()=>{
document.getElementById('show').click()
console.log('show')
}
hm=()=>{
document.getElementById('hide').click()
console.log('hide')
}
</script>
When the functions are called they do get executed (cause i can see the console.log) but the button click never gets executed. although when I tried the below jQuery the sm() got executed with all its lines(including the click)
$("#ss").ready( function(){
document.getElementById('show').click()
console.log("show")
});
the whole idea is that I want to show a modal when the page starts loading (with loading spinner) and then when the page is fully loaded (including getting database data and inserting them into a table). the modal gets automatically hidden
i prefer vanilla js rather than jquery

Getting a jQuery function to fire

I have a very simple jQuery function
$('#bnAddDegree').click(function () {
alert("bnAddDegree Loaded");
});
I have broken my site into different pieces based upon what the user clicks. If they click on a tab in the menu to load a section I call a partial_html page and load the section into the center div. If I put the code above into the main page load it will not fire. If I add an external js file and load it when the page loads it will not fire, I think because the elements are not initialized yet. If I put it into an external js page that is loaded after the partial_html is loaded it will not fire. If I put it ON the partial_html page with a tag it DOES fire. If I put a simple javascript function
function testFile() {
alert("File Loaded");
}
In the places that the jQuery code will not fire it works fine.
Is there something special that I'm missing with jQuery?
When I load the javascrip file I use
$.getScript("js/biosketch.js")
And test it with the simple javascript file and it works fine but not the jQuery call.
You need to use delegated event handlers since you are modifying the DOM dynamically.
$(document).on('click', '#bnAddDegree', function () {
alert("bnAddDegree Loaded");
});

location.reload(), Javascript,HTML

I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}

AJAX stop working on loading same site different PHP id

So i have a website that I'm doing for a school project. It's supposed to be like PasteBin. So on the right theres a different div (Uued koodid) that shows newest pastes. On click, they are supposed to show what they include using AJAX to refresh the left div. This only works for 4 times and then stops, but URL is still changing. After refresh it changes again and works again for 4 more times.
In main.js i have
...
$.ajaxSetup({ cache: false });
...
$(".uuedKoodid").click(function () {
$(".left-content").load(document.location.hash.substr(1));
});
...
EDIT:
Also other AJAX functions work. If I log in, I can switch between settings and profile perfectly but still cannot watch new codes
When you replace right menu with new code (from ajax call) you don't attach click event again on .uuedKoodid items so they don't do anything. You need to attach event again or attach it like this:
$(document).on('click', '.uuedKoodid', function () {
$(".left-content").load(document.location.hash.substr(1));
});
Edit:
As you noticed this will cause small problem. onclick event run before browser run standard link action. First you load ajax and then browser changes address. This way you are 1 action behind. Better solution than reading with delay (setTimeout) i think would be to read address directly from link:
$(document).on('click', '.uuedKoodid', function () {
var url = $(this).attr('href');
$(".left-content").load(url.substring(url.indexOf("#")+1));
});

Categories