Unable to set property 'onclick' of undefined or null reference [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I made new project in Visual Studio 2015. It's JavaScript Windows App. I'm trying to make "Hello" application, but when i want compile it i get this error:
0x800a138f - JavaScript runtime error: Unable to set property 'onclick' of undefined or null reference
My code:
document.getElementById("button").onclick = function () {
var jmeno = document.getElementById("Jmeno").value
var pop = new Windows.UI.Popups.MessageDialog("<%=Ahoj.Clientid%>" + jmeno);
pop.showAsync()
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App1</title>
<!-- WinJS references -->
<link href="WinJS/css/ui-dark.css" rel="stylesheet" />
<script src="WinJS/js/base.js"></script>
<script src="WinJS/js/ui.js></script>
<!-- App1 references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="js/zdravic.js"></script>
</head>
<body class="win-type-body">
<header>
<h1>Hello user! :)</h1>
</header>
<section>
<input id='Jmeno' type="text" placeholder="Zadej své jméno"/>
<button id="button">Klikni na mě!</button>
</section>
</body>
</html>
And for more, default.css doesn't work for me. Like it wouldn't be there. And yes, i have link it there.

You are trying to access an element, which has not been loaded yet,
try:
window.onload=function(){
document.getElementById("button").onclick = function () {
var jmeno = document.getElementById("Jmeno").value;
var pop = new Windows.UI.Popups.MessageDialog("<%=Ahoj.Clientid%>" + jmeno);
pop.showAsync();
}
}

Related

Running JavaScript libraries (Looper) in Blazor Server-side - some javascript code is not running

I am trying to implement Looper theme to my blazor server-side app, and I have the javascript libraries referenced at the end of the in _Host.cshtml.However some scripts in theme.min.js is not running. Why?
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script src="_framework/blazor.server.js"></script>
My problem is that while
<div data-toggle="drowndown"></div> works, but hamburger menu toggle
<button class="hamburger hamburger-squeeze mr-2" type="button" data-toggle="aside-menu" aria-label="toggle aside menu"><span class="hamburger-box"><span class="hamburger-inner"></span></span></button>
does not work. What am I missing here? What am I doing wrong? My theme change script also isn't running. If I step through theme.js and I can see that this script runs when blazor is not active (commenting out blazor.js) but with blazor active, this script does not run.
(line 610) in /library/javascript/theme.js
}, {
key: "toggleAside",
value: function toggleAside() {
var _this4 = this;
var $trigger = $('[data-toggle="aside"]');
$trigger.on('click', function () {
var isShown = $('.app-aside').hasClass('show');
$trigger.toggleClass('active', !isShown);
if (isShown) _this4.hideAside();else _this4.showAside();
});
}
My educated guess is that theme.js is using something that blazor does not allow? Is anybody experienced enough with Looper theme (or with javascript in general) to know why it wouldn't work? Particularly the hamburger toggle and the theme switching code
(line 1992 in /library/javascript/theme.js)
var Looper = function () {
var Looper = new Theme(); // toggle skin thought button
$('[data-toggle="skin"]').on('click', function (e) {
e.preventDefault();
var skin = Looper.skin === 'dark' ? 'default' : 'dark';
Looper.setSkin(skin); // we need to refresh our page after change the skin
location.reload();
}).each(function () {
var isDarkSkin = Looper.skin === 'dark';
var $icon = $(this).find('.fa-moon');
if (isDarkSkin) {
$icon.addClass('far');
$icon.removeClass('fas');
}
}); // make it global
return Looper;
}();
This is the website https://worshipground.azurewebsites.net/ You can use the inspector tool to see that blazor has been correctly loaded and all the javascript files are loaded in /library/javascript and /library/vendor/...
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- End Required meta tags -->
<title> Starter Template | Looper - Bootstrap 4 Admin Theme </title>
<base href="~/" />
<meta name="theme-color" content="#3063A0">
<link rel="apple-touch-icon" sizes="144x144" href="Library/apple-touch-icon.png">
<link rel="shortcut icon" href="Library/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:400,500,600" rel="stylesheet">
<link rel="stylesheet" href="/Library/vendor/open-iconic/font/css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="/Library/vendor/fontawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="/Library/stylesheets/theme.min.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/theme-dark.min.css" data-skin="dark">
<link rel="stylesheet" href="/Library/stylesheets/custom-app.css">
<link rel="stylesheet" href="/Library/stylesheets/custom.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/custom-dark.css" data-skin="dark">
<script>
var skin = localStorage.getItem('skin') || 'default';
var isCompact = JSON.parse(localStorage.getItem('hasCompactMenu'));
var disabledSkinStylesheet = document.querySelector('link[data-skin]:not([data-skin="' + skin + '"])');
// Disable unused skin immediately
disabledSkinStylesheet.setAttribute('rel', '');
disabledSkinStylesheet.setAttribute('disabled', true);
// add flag class to html immediately
if (isCompact == true) document.querySelector('html').classList.add('preparing-compact-menu');
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
You may find you have your work cut out in terms of making a JavaScript heavy template work nicely in Blazor.
You will probably need to utilise IJSRuntime
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0
I think I know where this problem comes from! If you comment out the following code on the "Host.cshtml" file, this problem will most likely go away!
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
But!!!! You will get some javascript errors related to "WebSocket" instead! something like this:
"WebSocket is not in the OPEN state"
Or
"Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State."
The cause of these errors is a conflict between "pace.min.js" file and "blazor.server.js" file! You can check this link for more information and get more help

Why is the console throwing " Cannot read property 'addEventListener' of null"? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
How to getElementByClass instead of GetElementById with JavaScript?
(8 answers)
Closed 2 years ago.
I've declared all the variables and then stored all the elements accordingly.
Then I've declared two functions.
Finally I've created two event listeners, where the two functions I created have been passed as call back.
Although I seem to have followed all the proper steps I can't identify why the console is throwing : "Uncaught TypeError: Cannot read property 'addEventListener' of null at index.js:32".
If you could point out where I've made a mistake that would be great.
var elForm, elSelectPackage, elPackageHint, elTerms, elTermsHint;
elForm = document.getElementById("formSignUp");
elSelectPackage = document.getElementById("package");
elPackageHint = document.getElementById("packageHint");
elTerms = document.getElementById("terms");
elTermsHint = document.getElementById("termsHint");
function packageHint(){
var package = this.options[this.selectedIndex].value;
if(package === "Monday") {
elPackageHint.innerHTML = "You get 10% off";
} else {
elPackageHint.innerHTML = "Wise choice"
}
}
function checkTerms(event) {
if (!elTerms.checked) {
elTermsHint.innerHTML = "you must agree to term & conditions"
event.preventDefault();
}
}
elForm.addEventListener('submit', checkTerms, false);
elSelectPackage.addEventListener("change", packageHint, false);
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Practise App</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 id="packageHint"></h1>
<form method="post" id="formSignUp" action="http://www.example.org/register">
<select class="package" name="">
<option value="">Monday</option>
<option value="">Tuesday</option>
<option value="">Wednesday</option>
</select><br>
</form>
<input id="terms" type="checkbox" name="" value="">
<div>check to agree terms and conditions</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
Because you do :
elSelectPackage = document.getElementById("package");
But package is a class, not an ID

How to add event with Javascript to an html tag

I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>

"Cannot read property 'addEventListener' of null" only appears after exporting from codepen

I was using codepen to make a custom homepage
it worked until I exported it than...
Cannot read property 'addEventListener' of null.
and all my animations didn't work.
heres my JS code
window.onload = function(){
const left = document.querySelector(".left");
const right = document.querySelector(".right");
const container = document.querySelector(".container");
left.addEventListener("mouseenter", () => {
container.classList.add("hover-left");
});
left.addEventListener("mouseleave", () => {
container.classList.remove("hover-left");
});
right.addEventListener("mouseenter", () => {
container.classList.add("hover-right");
});
right.addEventListener("mouseleave", () => {
container.classList.remove("hover-right");
});
}
and my HTML
<!DOCTYPE html>
<html lang"en">
<head>
<meta charset="utf-8">
<title>...</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="script.js"></script>
<div>
</head>
<body>
<div class="split left">
<h1>My Email</h1>
Go There
</div>
<div class="split right">
<h1>Google</h1>
Go There
</div>
</div>
</body>
</html>
I hope someone can help me fix this error
You need to run your javascript on page load. In script.js as the elements do not yet exist when it is currently running:
window.onload = function(){
// rest of your code
}
Codepen does this automatically for you, which is why it worked there.
Edit: Your opening <div> element is also inside the <head> element and is missing the class="container" attribute.

What error is there in the jQuery [duplicate]

This question already has answers here:
jQuery: get the file name selected from <input type="file" />
(8 answers)
Closed 5 years ago.
Below in the code the vanilla javascript version works fine but the jQuery one I tried to code does not produce the update to the input's text. What error is there in the jQuery one as I cannot seem to spot it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Total Tutor </title>
<link type="text/css" rel="stylesheet" href="query.css">
<script src="../jquery.js"></script>
</head>
<body>
<div id="main">
<button class="fileUpload">
<input id="uploadBtn" type="file" class="upload">
</button>
<input id="uploadFile" placeholder="0 files selected" disabled="disabled">
</div>
</body>
</html>
<script>
$("#uploadBtn").change(function() {
var value = $(this).val();
$("#uploadFile").val(value);
});
//this works fine
// document.getElementById("uploadBtn").onchange = function () {
// document.getElementById("uploadFile").value = this.value;
// };
</script>
Please try this :
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
alert(fileName);
// do whatever you want to do with file name
});
});

Categories

Resources