Getting null value on the querySelector - javascript

I try to copy paste the code from Mozilla's getting started with Javascript tutorial
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox2.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
I am getting an error "Cannot set property 'onclick' of null". How can correct the code?
I am just getting started with javascript. please forgive me if it is a silly mistake from my part.

You might be trying to assign the click handler before the element has been rendered so the query selector will not find the img tag. Try executing your script after the page has rendered like so
window.onload = function () {
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox2.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
}

Related

Cannot read property 'on' of null conflict

I have a script that works fine until I add another script. When the other script is added I get the console error.
Uncaught TypeError: Cannot read property 'on' of null at mapForm
I'm integrating my own script with JotForm so I have a couple libraries loading. I tried to set a no conflict without luck.
https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js
function mapForm() {
var JotFirst = document.getElementById("first_4"),
ACFirst = document.getElementById("firstname");
JotFirst.addEventListener('input', function() {
ACFirst.value = JotFirst.value;
});
var JotLast = document.getElementById("last_4"),
ACLast = document.getElementById("lastname");
JotLast.addEventListener('input', function() {
ACLast.value = JotLast.value;
});
JotProd = $("input[type='checkbox'][id='input_5_1000']");
ACProd = $("input[type='checkbox'][id='extra_mf_1_515']");
JotProd.on("change", function() {
ACProd.prop("checked", this.checked);
});
$("#input_5_custom_1000_0").change(function() {
var el = $(this) ;
if(el.val() === "Option Two" ) {
document.getElementById("extra_mf_3_516").selectedIndex = "1";
}
else if(el.val() === "Option Three" ) {
document.getElementById("extra_mf_3_516").selectedIndex = "2";
}
});
}
window.onload = mapForm;
The above code works fine on it's own.
https://cdn.jotfor.ms/static/prototype.forms.js
https://cdn.jotfor.ms/static/jotform.forms.js
When these are introduced my script stops working. I've searched and searched and tried everything I know to solve.
Here's the page in question: https://btwebnetwork.com/scripts/multi-submission-form/AllClients.php
You have to make sure taht the JotProd variable is not NULL, you can do it like this
if(JotProd){
JotProd.on("change", function() {
ACProd.prop("checked", this.checked);
});
}

Simpel image toggle function won't work (no jQuery)

I have been trying to make this simpel image toggle on click function work but I am not sure what is wrong. I have to use querySelector and addEventListener, also jquery is not allowed. Could anyone please help me figure this out?
document.querySelector(".imageClass").addEventListener("click", function () {
var img = this.src;
if(img.src == "/image/location1.png") {
img.src = "/image/location2.png";
} else {
img.src = "/image/location2.png";
}
});
I'm getting this error:
document.querySelector(...).addEventlistener is not a function(...)
Getting a property would most likely return an absolute URL, and you really want to make sure you check the attribute, not the property.
Also, you're accesing src twice, first by doing var img = this.src then by doing img.src
And your condition does the same thing in both cases
document.querySelector(".imageClass").addEventListener("click", function () {
var img = this;
var src = img.getAttribute('src');
if( src == "/image/location1.png" ) {
img.src = "/image/location2.png";
} else {
img.src = "/image/location1.png";
}
});
Recieve your event by passing it with your parameters. From there you can access the target element of the event and get its src attribute.
document.querySelector(".imageClass").addEventListener("click", function (e) {
var img = e.target;
if(img.src == "/image/location1.png") {
img.src = "/image/location2.png";
} else {
img.src = "/image/location2.png";
}
});

bLazy image loader, how to get data src on error?

I am using blazy image loader and I am trying to get the data src from the element on error. Basically if the image is not found or invalid I want to change the last 4 letters of the image src, but I cannot figure out how to get the actual source. Here is my code:
var bLazy = new Blazy({
loadInvisible: true,
error: function (ele, msg) {
if (msg === 'missing') {
var dsrc = ele.src();
var fallback = dsrc.replace('y.jpg','b.jpg');
ele.src(fallback);
} else if (msg === 'invalid') {
console.log(this);
}
},
success: function(ele,msg){
//console.log(ele.parseJSON());
console.log(this);
}
});
I also tried ele.attr('data-src'); and that didn't work either. When I look at the console for console.log(ele) I get the actual image not the element.
Anyone who could help... please!!
If you would like to get the "src" attribute, you can use the $(ele).data("src") or $(ele).attr("data-src") with JQuery.
After you can modify.
;(function() {
// Initialize
var bLazy = new Blazy({
error: function(ele, msg){
if(msg === 'missing'){
// Data-src is missing
console.log(msg);
} else if(msg === 'invalid'){
// Data-src is invalid
//console.log( $(ele).data("src") );
var src = $(ele).data("src");
src = src.substring(0, src.length - 4) + 'b.jpg';
//or
//src = src.replace('y.jpg','b.jpg');
$(ele).attr("src",src);
}
}
});
})();

processing.js change script source

I need to find a way where I can dynamically change the source of a processing script inside an HTML document.
This is the embedded script which works fine:
<script type='application/processing' src='sketch.txt' id="applet">
</script>
Now I try to change the source:
$('#applet').attr('src', 'sketch2.txt');
alert($('#applet').attr('src'));
The alert shows that the source was changed to 'sketch2.txt' but the applet still remains the same. I think I need to refresh the script in some way.
Thank you in advance for any help!
I believe you have to manually attach each proc to the canvas, instead of just changing the the source file. This worked here:
function first_call(processing) {
processing.size(300,300);
processing.background(100);
var called = false;
processing.draw = function() {
if (!called) { processing.println("called #1"); called = true; }
}
}
function second_call(processing) {
processing.size(400,400);
processing.background(200);
var called = false;
processing.draw = function() {
if (!called) { processing.println("called #2"); called = true; }
}
}
var canvas = document.getElementById('canvas1');
var processingInstance = new Processing(canvas, first_call);
var processingInstance = new Processing(canvas, second_call);

Uncaught ReferenceError: X is not defined

This code is being used on a Chrome Extension.
When I call the "showOrHideYT()" function, I get a
"Uncaught ReferenceError: showOrHideYT is not defined | (anonymous
function) | onclick"
This code will search for youtube links in a page, and it will add a button (it's really a div with an event) next to the link to show the iframe with the embedded video, pretty much like Reddit Enhancement Suite. Consider the code, per se, incomplete. I just want to know what am i missing when i call the "showOrHideYT(frameZES12345)" function.
if needed, i can provide manifest.json.
Thanks
function showOrHideYT(id)
{
var YTvidWidth = 420;
var YTvidHeight = 315;
frameYT=getElementById(id);
console.log(frameYT.style.visibility);
if (frameYT.style.visibility == "hidden")
{
frameYT.style.width = YTvidWidth+"px";
frameYT.style.height = YTvidHeight+"px";
frameYT.style.visibility = "visible";
}
if (frameYT.style.visibility == "visible")
{
frameYT.style.width = "0px";
frameYT.style.height = "0px";
frameYT.style.visibility = "hidden";
}
};
// DOM utility functions
function insertAfter( referenceNode, newNode ) {
if ((typeof(referenceNode) == 'undefined') || (referenceNode == null)) {
console.log(arguments.callee.caller);
} else if ((typeof(referenceNode.parentNode) != 'undefined') && (typeof(referenceNode.nextSibling) != 'undefined')) {
if (referenceNode.parentNode == null) {
console.log(arguments.callee.caller);
} else {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
}
};
function createElementWithID(elementType, id, classname) {
obj = document.createElement(elementType);
if (id != null) {
obj.setAttribute('id', id);
}
if ((typeof(classname) != 'undefined') && (classname != '')) {
obj.setAttribute('class', classname);
}
return obj;
};
///////////////////////////////////////
$(document).ready(function() {
var vidWidth = 420;
var vidHeight = 315;
var linksSemID = document.getElementsByTagName("a") ;
for (var i = 0; i < linksSemID.length; i++){
if (/id=$/.test(linksSemID[i].href)) links[i].href += "1";
}
i=0;
var youTubeRegExp = /(?:v=)([\w\-]+)/g;
var forEach = Array.prototype.forEach;
var linkArray = document.getElementsByTagName('a');
forEach.call(linkArray, function(link){
linkArray.id="zes" + i++;
var linkTarget = link.getAttribute('href');
if (linkTarget!=null)
{
if (linkTarget.search(youTubeRegExp) !=-1)
{
console.log (linkTarget);
idVideo=linkTarget.match(/(?:v=)([\w\-]+)/g);
//idVideo = idVideo.replace("v=", "");
//add buton
botaoMais = document.createElement('DIV');
botaoMais.setAttribute('class','expando-button collapsed video');
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
insertAfter(link, botaoMais);
//add iframe
ifrm = document.createElement('IFRAME');
ifrm.setAttribute('src', 'http://www.youtube.com/embed/'+ idVideo);
ifrm.style.width = '0px';
ifrm.style.height = '0px';
ifrm.style.frameborder='0px';
ifrm.style.visibility = 'hidden';
ifrm.setAttribute('id', 'frameZES' + i);
insertAfter(link, ifrm);
}
}
});
});
When you use setAttribute with a string, the event will be executed in the context of the page. The functions which are defined in a Content script are executed in a sandboxed scope. So, you have to pass a function reference, instead of a string:
Replace:
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
With:
botaoMais.addEventListener('click', (function(i) {
return function() {
showOrHideYT("frameZES"+ i);
};
})(i));
Explanation of code:
(function(i) { ..})(i) is used to preserve the value of i for each event.
Inside this self-invoking function, another function is returned, used as an event listener to click.
I see that you are using jQuery in your code. I personally think if we are using a library like jQuery, then we should not mix the native javascript code and jQuery code.
You can use jQuery bind to bind your the functions you need to call on dom ready.
Read below to know more.
suppose you want to call a javascript function on a button click, Here is the HTML for the same.
<div id="clickme">
<input id= "clickmebutton" type="button" value = "clickme" />
</div>
suppose "test" is the function you need to call, here is the code for test function.
function test() {
alert("hello");
}
you now need to bind the test function on the button click.
$(document).ready(function() {
$("#clickmebutton").bind("click", function(){
// do what ever you want to do here
test();
});
});

Categories