Does DOMContentLoaded works in Django? - javascript

Trying to get my button working. Project is setup on Django, using pure JS.
My JS script button.js:
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('exchange-button');
console.log("Button: " + btn); // Button: nu;;
if (btn) {
btn.addEventListener('click', () => {
console.log('btn clicked');
});
} else {
console.log("Not Working")
}
});
And usage in html declared in head tag:
<div>
<button class="exchange-button">Get Exchange rate</button>
</div>
{% load static %}
<script
src="{% static 'js/button.js' %}">
</script>
When Im checking if button exists, its not, the button is null and gettig same error all the time:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at HTMLDocument. (button.js:5:7)
Script is working perfectly when Im using pure html and js in other project.
What am I doing wrong?
Thanks for help

Related

Uncaught TypeError: Cannot read properties of undefined (reading 'get') at HTMLInputElement.geocodio

I am having issues trying to run an API using Geocodio. This is set up through WordPress and I would really appreciate any help I can get!
Everything works up until the actual API itself has to run. The Geocodio documentation states that it runs "using a jQuery AJAX call". I have tried multiple script sources that claim to fix the problem, but I get the error that "superfish() is not a function" or that "Cannot read properties of undefined (reading 'get')".
<head>
<script src="jQuery.js"></script>
<script src="superfish.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('ul.sf-menu').superfish();
});
</script>
</head>
<body>
<input type="text" id="myTxt" style="width: 400px;" placeholder="Type Your Address Here!"></input>
<input type="submit" id="myBtn" value="Search Now!"></input>
<script>
var submit = document.getElementById("myBtn")
var myInput = document.getElementById("myTxt")
submit.addEventListener("click", geocodio)
function geocodio() {
if(myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
$.get('https://api.geocod.io/v1.7/geocode?q='+ encodeURIComponent(myInput)
+'&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results)});
}
};
</script>
</body>
You must be using some strange version of jQuery that forces you to refer to it as jQuery and not $. Odd, I thought all versions of jQuery also set up the $ global.
Try replacing $ with jQuery inside geocodio():
function geocodio() {
if (myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
jQuery.get('https://api.geocod.io/v1.7/geocode?q=' + encodeURIComponent(myInput.value)
+ '&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results);
});
}
}
(also fixed: encode myInput.value instead of encoding whole input)
If that doesn't work, perhaps jQuery.js failed to load. Check the console messages and/or network trace tab in the developer tools.
If that doesn't work, try stepping thru the code using the JavaScript debugger built in to your browser (short tutorial video).

correct javasript code execution in flask

I tried to use click on button:
#app.route("/")
def test_edition_open():
return render_template("index.html")
my index.html file is:
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
The main part is just two buttons:
<div class = "counter">
<button class = "minus">-</button>
<div class = "result">1</div>
<button class = "plus">+</button>
</div>
I tried to make My script.js file work in flask. The code is very simple, it should add numbers by clicking on button:
const plus = document.querySelectorAll('.plus');
const minus = document.querySelectorAll('.minus');
const result = document.querySelectorAll('.result');
function min()
{
return function (ev)
{
if (ev.target.nextElementSibling.innerHTML > 0)
{
return --ev.target.nextElementSibling.innerHTML;
}
}
}
function pl()
{
return function (ev)
{
return ++ev.target.previousElementSibling.innerHTML;
}
}
minus.forEach(function (dominus)
{
dominus.addEventListener('click', min());
})
plus.forEach(function (doplus)
{
doplus.addEventListener('click', pl());
})
In https://playcode.io this code worked well. How should I solve this problem?
Make sure that script file successfully connected to html file. to check this add console.log("File Connected") in your script.js file. Then open your browser console to check that console message is logged correctly. If not then try to linked your static file correctly. How to set static_url_path in Flask application
Or you can put your Javascript code in html file using script tag.
Something like this:
<script> your javascript code here</script>

JavaScript function only works after page reload

I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>

Chrome Extension to pull text from script

I'm attempting to pull "webId%22:%22" var string from a script tag using JS for a Chrome extension. The example I'm currently working with allows me to pull the page title.
// payload.js
chrome.runtime.sendMessage(document.title);
// popup.js
window.addEventListener('load', function (evt) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'payload.js'
});;
});
// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
document.getElementById('pagetitle').innerHTML = message;
});
//HTML popup
<!doctype html>
<html>
<head>
<title>WebID</title>
<script src="popup.js"></script>
<script src="testButton.js"></script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<p id="body"></p>
<h3>It's working</h1>
<p id='pagetitle'>This is where the webID would be if I could get this stupid thing to work.</p>
</body>
</html>
What I am trying to pull is the webID from below:
<script if="inlineJs">;(function() { window.hydra = {}; hydra.state =
JSON.parse(decodeURI("%7B%22cache%22:%7B%22Co.context.configCtx%22:%7B%22webId%22:%22gmps-salvadore%22,%22locale%22:%22en_US%22,%22version%22:%22LIVE%22,%22page%22:%22HomePage%22,%22secureSiteId%22:%22b382ca78958d10048eda00145edef68b%22%7D,%22features%22:%7B%22directivePerfSwitch%22:true,%22enable.directive.localisation%22:true,%22enable.directive.thumbnailGallery%22:true,%22enable.new.newstaticmap%22:false,%22disable.forms.webId%22:false,%22use.hydra.popup.title.override.via.url%22:true,%22enable.directive.geoloc.enableHighAccuracy%22:true,%22use.hydra.theme.service%22:true,%22disable.ajax.options.contentType%22:false,%22dealerLocator.map.use.markerClustering%22:true,%22hydra.open.login.popup.on.cs.click%22:false,%22hydra.consumerlogin.use.secure.cookie%22:true,%22use.hydra.directive.vertical.thumbnailGallery.onpopup%22:true,%22hydra.encrypt.data.to.login.service%22:true,%22disable.dealerlocator.fix.loading%22:false,%22use.hydra.date.formatting%22:true,%22use.hydra.optimized.style.directive.updates%22:false,%22hydra.click.pmp.button.on.myaccount.page%22:true,%22use.hydra.fix.invalid.combination.of.filters%22:true,%22disable.vsr.view.from.preference%22:false%7D%7D,%22store%22:%7B%22properties%22:%7B%22routePrefix%22:%22/hydra-graph%22%7D%7D%7D")); }());</script>
You have inline code in onclick attribute which won't work, see this answer.
You can see an error message in devtools console for the popup: right-click it, then "Inspect".
The simplest solution is to attach a click listener in your popup.js file.
The popup is an extension page and thus it can access chrome.tabs.executeScript directly without chrome.extension.getBackgroundPage(), just don't forget to add the necessary permissions in manifest.json, preferably "activeTab".
For such a simple data extraction you don't even need a separate content script file or messaging, just provide code string in executeScript.
chrome.tabs.executeScript({
code: '(' + (() => {
for (const el of document.querySelectorAll('script[if="inlineJs"]')) {
const m = el.textContent.match(/"([^"]*%22webId%22[^"]*)"/);
if (m) return m[1];
}
}) + ')()',
}, results => {
if (!chrome.runtime.lastError && results) {
document.querySelector('p').textContent = decodeURI(results[0]);
}
});

Sharepoint Document Library - Filename to title using javascript

Good evening!
I had a working functionality on a sharepoint document library. It's purpose was to copy the name of a file to the title column.
It was working for a long time but after an update to the sharepoint platform it stopped working and i can't figure out why.
The code:
<input type="button" onclick="updateTitleFromName()" value="Update Title from Name" />
<script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript">
function updateTitleFromName(){
var q, res, uRes, count;
count = 0;
q = "<Where><IsNull><FieldRef Name='Title' /></IsNull></Where>";
res = spjs_QueryItems({"listName":_spPageContextInfo.pageListId,"query":q,"viewFields":["ID","FileLeafRef"]});
if(res.count === 0){
alert("No files without title found.");
return;
}
if(!confirm("There are "+res.count+" files to update. The page will appear as frozen while the script is working.\n\nContinue?")){
return;
}
$.each(res.items,function(i,item){
uRes = spjs_updateItem({"listName":_spPageContextInfo.pageListId,"id":item.ID,"data":{"Title":item.FileLeafRef.split(";#")[1]}});
if(!uRes.success){
alert("Could not update the file: "+item.FileLeafRef+" due to the follwing error:\n\n"+uRes.errorText);
}else{
count += 1;
}
});
alert("Updated "+count+" files.");
location.href = location.href;
}
</script>
The error is: TypeError: $spjs is null. And it occurs inside the library spjs-utility library on the spjs_QueryItems call.
Maybe this could be due to a conflictuous library that as added during the updated, but how can i debug this?
Also, if this doesn't work, wouldn't it be simpler to do the same with jQuery? Thats what i'm trying right now, but i'm a beginner as you must have perceived.
Thanks in advance.
Best
I would test if JQuery is loaded or not in your updateTitleFromName function:
if (window.jQuery) {
alert('loaded');
} else {
alert('not loaded');
}
if it is not loaded, try to reference your scripts with absolute urls to see if you can load them:
<script type="text/javascript" src="http://myportal/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://myportal/Scripts/spjs-utility/spjs-utility.js"></script>

Categories