Catch22 - HTML waiting for JS, JS waiting for HTML - javascript

I'm a newbie trying to write a JS/HTML report generator based on criteria which I submit in an HTML form. The plan eventually is to use PHP/mySQL to manipulate a database and return results but for now I'm just trying to build the HTML/CSS/JS and I've got stuck. I have attributed a JS function to a button in the <body> like so:
<input type="button" id="reportButton" value="Generate Report" onclick="showCriteria()">
I included a script in the <head> as follows:
<script>var showCriteria = function(){ My JS code...}</script>.
This function simply does some date manipulation and displays the result in a div on the same page like so:
document.getElementById("endDate").innerHTML = "to "+endDay+" "+endMonthName+" "+endYear;
But I get Uncaught TypeError: Cannot set property 'innerHTML' of null. So I searched the forum and discovered that this can sometimes be caused by not waiting for the window to load. So I wrapped the script as follows:
<script>
window.onload = function()
var showCriteria = function(){ My JS code...}
That solved the initial error but I then get Uncaught ReferenceError: showCriteria is not defined
It seems like I'm in a Catch22. I get the first error because the script is running before the window has loaded. I fix that by waiting for the window to load only to find that the HTML is waiting for my script to define my JS function.
Any advice gratefully received.
Report Generator screenshot
Window.load script

You've almost got the solution. At least you've got all the right elements.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};
This will make it so the button does not function until the page is ready.
You also need to remove the onclick from the button.

When you put the showCriteria function inside window.onload, please make sure it is accessible by the DOM, i.e. window.showCriteria.
<script>
window.onload = function()
window.showCriteria = function(){ My JS code...}
...
Beside using onclick on html, you can use add listener to listen the click event on that element.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

SharePoint 2013 JavaScript OnClick event

On our SharePoint 2013 page we have a button which runs an EXE
I want to generate a JS Alert when the button is clicked so that users know to click RUN
The buttons are being generated by a Content Search Web Part which is reading from a list with a Title and URL field.
For the EXE my url is this: file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe
I tried to embed the JavaScript inline using code such as: javascript:open('file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe') or more basically: JavaScript:alert('TEST');
But SharePoint is giving me an "Invalid URL" message when I try to embed JS in this manner.
I have instead now moved to a Script Editor Web Part and am trying to add the Alert to the OnClick event of my button but this is where I am stuck.
My Script Editor code:
<script style="javascript;">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick="javascript:alert('event has been triggered')";</script>
Here is an image of the IE Debug screen which is how I'm pulling the ID. This H2 element is wrapped in an HREF which is wrapped in two DIV tags which make up an LI
With the above snippet IE Debug is giving me this error message:
Unable to set property 'onclick' of undefined or null reference
I am hoping that this is as simple as misplaced quotations, or assigning the OnClick event to the wrong element, but I'm spinning my wheels. Any help appreciated and I'm happy to clarify
You should associate a function to the onclick event on img
<script type="text/javascript">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick = function () {
alert('event has been triggered');
};
</script>
Say that your page is in the SitePages library and you use jQuery, you can add it to a folder called "js" in the SiteAssets folder, then go back to your Script Editor WP and do it like this:
<script src="../SiteAssets/js/jquery-3.6.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('input[id*="csr4_pictureOnTop_line1"]').on('click', function() {
alert('event has been triggered');
});
</script>

Iframe Input has uncaught TypeError: Cannot set property 'value' of null

I have an input inside an iframe that I would like to put in a preloaded value after the page has loaded. I've put in this code so far:
<script>
jQuery('iframe').load(function(){
jQuery('iframe').contents().find('input#ysi_subject').bind('change',function(e) {
var title_name = "DO I LOOK LIKE I'M WORKING?";
jQuery('input#ysi_subject').val(title_name);
});
});
</script>
but when I look at the console log, I get this error:
Uncaught TypeError: Cannot set property 'value' of null
Can anyone help explain why it's not catching the input?
This is because you are trying to access the DOM prior to the DOM elements actually being loaded, so any references to the DOM in this case will output null. Place the code in a $(document).ready() handler in order for this to work:
... <!-- jQuery reference -->
<script>
$(document).ready(function() {
// your code that you are trying to run
});
</script>
* Note that I simplified it down to show what I am really talking about.
The change event is firing from within the iframe back to the parent window.
$("input#si_subject") does not exist in the parent window.
jQuery('iframe').load(function(){
jQuery('iframe').contents().find('input#ysi_subject').bind('change',function(e) {
var title_name = "DO I LOOK LIKE I'M WORKING?";
// this would work
jQuery('iframe').contents().find('input#ysi_subject').val(title_name);
// this is better
$(this).val(title_name);
});
});

How to run a javascript function when a page dynamically loads content

I am currently writing some Javascript code that adds some tags across text in an HTML file after the page loads. I use the
window.onload
method for achieving this.
However, I am facing an issue in pages like google plus, where you get more content as you scroll down. Is there a way of calling my JS function when such a page adds more content?
Thanks
Akshay
There are several ways how to get this working. You can either use jquery like this:
$('#mydiv').bind("DOMSubtreeModified",function(){
// your code goes here
alert('changed');
});
Note that this is not supported in IE8( and below).
Or you can run loop and continuously fire the desired code:
var interval = setInterval(function() {
// your code goes here
}, 1000);
Fiddle: http://jsfiddle.net/8RF5r/5/

Access HTML element later in document through JavaScript

I am just starting out with JavaScript and I have a simple code that sends a value to an element with id p. I am currently declaring this function in a <script> in the <head> element of my document.
function writeP(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
writeP(results);
When I have this listed within the <head> element and run the webpage, firebug throws this error at me: TypeError: document.getElementById(...) is null.
However, if I move the code block into a <script> tag beneath the element and then reload the webpage, no problems and the script works as it should. Is there any reason for this, and a way I could make this work so I wouldn't have to define my functions beneath the element or include a onload on my body element?
Thanks for your help
Reason is that by the time your launch js code, DOM is not yet prepared, and JS can't find such element in DOM.
You can use window.onload (docs on W3schools) trigger to fire your functions after all elements are ready. It's same as having onload property on body element, but is more clear, as you can define it in your js code, not in html.
JS evaluates syncronically. Therefore, it does matter WHEN you declare the function. In this case, you're declaring it before the element actually exists.
Second, when you declare a function with that syntax, it does get eval'd inmediately. If you declared, instead
var writeP=function(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
you could save just the call to the end of the Doc, and leave the declaration at the beggining.
However, I would advise you to read a few jQuery tutorials to learn easier ways to deal with dom manipulation. Nobody runs raw JS for that task anymore.
jQuery includes an useful call to document ready event, which will save you a lot of headaches and is -IMHO- more efficient than the onload event. In this case, you would include the jQuery library somewhere in your code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and then add
<script>
jQuery(document).ready(function() {
var writeP=function(resultSet) {
jQuery('#p').html(resultSet.length);
};
writeP(resultSet);
});
</script>
just about anywhere in your document or an external js file, as it suits you.

Categories

Resources