Noob JavaScript error (Can't set property 'src' of null) - javascript

I have a simple error with my javascript file (Can't set property 'src' of null)
I am trying to change the image once in 1 second.
Here is my html code :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body >
<div class='bannerbg'>
<img src="img/2.jpg" alt="">
<div class='slider'></div>
</div>
</body>
</html>
Here is my JavaScript file:
images=new Array
(
"img/1.jpg",
"img/2.jpg",
"img/3.jpg"
);
function left() //this function change the index of the array of images
{
images.push(images.shift());
}
function change(){
i=document.querySelector("#bannerbg img");
i.src=images[0];
}
setInterval("left(); change()",1000);

Try this:
document.querySelector(".bannerbg img");
Your div has "bannerimg" as class, so you'll need to ude a period to tell the querySelector to look for a class.
The # is used to look for id properties, like this:
<div id='bannerbg'>
<img src="img/2.jpg" alt="">
<div class='slider'></div>
</div>
However, for maximum compatibility, I'd suggest adding a id to the image element:
<img src="img/2.jpg" alt="" id="myImage">
Then you can use document.getElementById("myImage") to access the specific element.
getElementById is one of the better supported DOM access functions, it will even work on IE versions as old as 5.5.
On a different note:
Your setInterval call is a bit of a bad practice. (See the explanation at the "code" parameter)
A better option would be to call it like this:
setInterval(function(){
left();
change();
},
1000);

Your selector comes up empty and thus the following attempt to set src fails.
In this line
<div class='bannerbg'>
you actually declare a class to that <div> and not an id. Within the selector, however, you use a #, which refers to ids. So either change the selector to use . as a class selector
i=document.querySelector(".bannerbg img");
or change your HTML to set an id instead of a class
<div id='bannerbg'>

Hey your using the id selector not a class selector # = id . = class. This means you dont select any element hence the error.
Try
document.querySelector(".bannerbg img");

Related

jQuery does not find IMG component by its ID

I have a webpage which contains such code:
<img class="img-qrcode" id="img_123.000.00.01"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:
$("#img_123.000.00.01")
The added screenshot shows that it returns an empty array.
Why does it not find the element with ID ?
Using an attribute selector for id, you don't have to worry about escaping the class selector (.)
let img = $("img[id='img_123.000.00.01']");
console.log(img.attr('src'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123.000.00.01"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
The a . character has special meaning in a selector (it starts a class selector) so you need to escape it. (Remember to escape the slash character in a string literal).
Generally it is easier to just avoid using . chapters in an id.
Find with ^
let img = $("img[id^='img_123']");
console.log(img.attr('src'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
When some special symbols are in the jquery selector, you need to add 『\\』
console.log($("#img_123\\.000\\.00\\.01"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01.png" style="display:none">
</body>
</html>
Since #id.className is a valid selector jQuery assumes it so and tries to find such element. In your case you will have to escape the dot.
Change $("#img_123.000.00.01") to $("#img_123\\.000\\.00\\.01") and it will work.
Official jQuery documentation(https://api.jquery.com/category/selectors/) states it clearly.
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?#[\]^{|}~` ) as a literal part of a name, it
must be escaped with with two backslashes

jQuery .html() method syntax

So here's the full function/for-loop. I'm basically trying to grab images from Flickr and present them using Lightbox.
If you don't need all this info, just scroll down to "WHAT'S WRONG WITH THIS SYNTAX?" The jQuery .html() method that follows is giving me trouble. How does the syntax work in this instance? Thank you!
$.getJSON(requestURL, function(flickrResponse) {
flickrResponse.items.forEach(function (item) {
// create a new a element and hide it
var $anchor = $("<a>").hide();
// set the href attribute of the a element to connect to the same Flickr image
// that the img element connects to
$anchor.attr("href", item.media.m);
// set the data-lightbox attribute, and use "Flickr" as the value of the attribute
$anchor.attr("data-lightbox", "Flickr");
// create a new JQuery element to hold the image
// but hide it so we can fade it in
var $img = $("<img>").hide();
// set the attribute to the url
// contained in the response
$img.attr("src", item.media.m);
// WHAT'S WRONG WITH THIS SYNTAX?
// Use the jQuery.html() method to set the img element as the innerHTML of the a element.
$($anchor).html($img);
// attach the img tag to the main
// photos element and then fade it in
$("main.photos").append($anchor);
$anchor.fadeIn();
});
});
The corresponding HTML file:
<!doctype html>
<html>
<head>
<title>Flickr App</title>
<link href="stylesheets/styles.css" rel="stylesheet">
<link href="stylesheets/lightbox.min.css" rel="stylesheet">
</head>
<body>
<header>
</header>
<main>
<div class="photos">
</div>
</main>
<footer>
</footer>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="javascripts/lightbox.min.js"></script>
<script src="javascripts/app-lightBox.js"></script>
</body>
</html>
In JS you only forgot to take the hide "var $img".
If you change line, it should work:
var $img = $("<img>").hide();
For:
var $img = $("<img>");
And you have to change this line:
$("main.photos").append($anchor);
For:
$("main .photos").append($anchor);
OR
$(".photos").append($anchor);
I don't know if the flickrResponse is correct
You just made a simple mistake. here is what you need to really do:
$($anchor).html('img');
Per it's signature, .html() method accepts either a string, or a function.
.html( htmlString )
.html( function )
Either you want to construct a string(html) representation of the image or use the .append() method which accepts a jQuery object, like so:
$anchor.append( $img )

Why doesn't my javascript return a url?

In my script i'm trying to get my Javascript script to return a URL, so I can use the URL as a background for the website.
Here is my code:
//background script
//backgrounds
Rblxscreenshot_zombietower = "http://saberman888etai.net/background_images/rblxscreenshot.png";
Rblxscreenshot_zombietower2 = "http://saberman888.netai.net/background_images/zombietower2.png";
Rblxscreenshot_deathrun = "http://saberman888.netai.net/background_images/deathrun_ice.png";
Rblxscreenshot_deathrun2 = "http://saberman888.netai.net/background_images/deathrun_lobby.png";
SCREENSHOTS = [
Rblxscreenshot_zombietower,
Rblxscreenshot_zombietower2,
Rblxscreenshot_deathrun2,
Rblxscreenshot_deathrun
];
function returnBackground(){
return SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)+1)];
}
And here is my HTML code:
<!DOCTYPE html>
<head>
<title>Saberman888's Website</title>
<link rel="stylesheet" type="text/css" href="theme.css"/>
<script type="text/javascript" src="background.js"/>
</head>
<body style="background-image:url(<script src="http://saberman888.netai.com/background.js">returnBackground()</script>);">
<div class="box">
<div style="text-align:center;">
<h1>Home</h1>
Home
Conlangs
Projects
</div>
<hr>
<div id="minibox" style="margin-left:100px;">
<h2>Conlangs</h3>
<ul>
<li>Florrum</li>
<li>Genie</li>
</ul>
</div>
<div id="minibox" style="margin-left:100px;">
<h2>Projects</h2>
<ul>
<li>DLBOX</li>
<li>QuarryLang</li>
</ul>
</div>
<div id="links">
My Youtube
My DeviantArt
My Twitter
<a href="8.42.96.39/User.aspx?ID=49027085
">My Roblox</a>
My Github
</div>
</div>
</body>
</html>
As you can see, in the HTML code it uses the function returnBackground() to get a URL to use as a background, but the background doesn't show up, any reason why?
If you try to mod with the length of the array, it will be always inside the range. This issue looks like an out of range error in the line below:
function returnBackground(){
return SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)+1)];
}
So replace it with:
function returnBackground(){
return SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)+1) % SCREENSHOTS.length];
}
Update
Just saw a basic mistake, you cannot use a <script> tag or any other tag for that instance, inside an attribute. That's a syntax error:
<body style="background-image:url(<script src="http://saberman888.netai.com/background.js">returnBackground()</script>);">
You cannot set the background URL like that. Instead you need to this way:
<body onload="returnBackground();">
And in the returnBackground() should set the background in this way:
document.body.style.backgroundImage = url;
Your full returnBackground() function:
function returnBackground(){
document.body.style.backgroundImage = SCREENSHOTS[Math.floor((Math.random() * SCREENSHOTS.length)) % SCREENSHOTS.length];
}
The way you're trying to include the script is incorrect.
As per the HTML5 specification, a script tag has to contain either a src attribute or script content inside the tags, not both. (The only allowed content for a script tag with src specified is documentation, i.e. comments.)
Quote on the script element:
If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.
(This wasn't correct before HTML5 either, but (I think) it was more ill-defined, so it might work in some browsers, but don't rely on this.)
Also, the script tag cannot be inlined within a style (or any other) attribute.
For example, one of your better options is modifying the script to retrieve the body DOM element and manipulates its style, its background-image specifically (taking a more imperative approach). Then just include this script inside a script tag into your HTML.
Praveen Kumar's suggestion of adding an onload event handler is probably even easier, but the script include has to be fixed regardless of which path you choose.

How to get two scripts src from iframe using jquery or vanilla javascript

How to get two scripts src from iframe using jquery or javascript
<div id="mytesting">
<iframe src="index.html" id="testing" >
<html>
<head>
<script src="http://google.com/javascript.js"></script>
<!-- i want to get below src the src will change every time -->
<script src="http://testing.com"></script>
<!-- i want to get above src the src will change every time -->
</head>
<body>
</body>
</html>
</iframe>
</div>
In this I want to get second src using jquery or javascript.
There's different ways you can select the src attribute in your code, I'd recommend you first give it an id like this:
<script id="myscript" src="http://testing.com/javascript.js"></script>
You can then select that element by its id using $("#myscript"). The code for getting the src attribute is
var source = $("#myscript").attr('src');
If you don't want to add an id attribute, you can use a different selector, for example, you can select the second script tag in the head like this: $("head script:nth-child(2)"). Be careful though, because if someone adds another script element in the head above this element, this will no longer work.

Attach an HTML block "more times" by avoiding code repetitions

Supposing that I've a block myBox defined as follows:
<div class="myBoxClass" id="myBox">
<h1>My Box</h1>
<img src="http://placehold.it/350x150" alt="My Picture" />
<p>Lorem Ipsum...</p>
</div>
Then, I've defined two containers, containerA and containerB:
<div id="containerA">
<!-- Attach MyBox -->
</div>
<div id="containerB">
<!-- Attach MyBox -->
</div>
I'd like to attach MyBox inside the two containers, by avoiding code repetitions.
Which is the best way to do that?
Note: I'm looking for a client-side solution, useful to define some responsive sections.
You can do that by,
$("#containerA,#containerB").html($('.myBoxClass').clone());
But be aware that id is going to be repeated. That makes the html invalid.
DEMO
And you can avoid the redundancy by giving them unique id after placing them into the DOM,
$("#containerA,#containerB")
.html($('.myBoxClass').clone())
.find('.myBoxClass').attr('id', function (i,val) {
return val + (i+1);
});
DEMO
If the give html structure of myBoxClass differs from, what you shown up here, by means of additional elements with id then you should write the code as per T.J said,
$("#containerA,#containerB")
.html($('.myBoxClass').clone())
.find('[id]').attr('id', function (i,val) {
return val + (i+1);
});
The server-side option is to wrap myBox in a PHP function (or some other server-side language) that echoes/returns the HTML and call said function in the place of your comments. The client-side option is to do the same with Javascript/jQuery. Both are relatively trivial implementations so I won't bother with examples unless you need one (but it's hard to recommend which to use without more info about your site/setup).
However, make sure you iterate the IDs as they must be unique (e.g. #myBox1 and #myBox2)
You can do like this,
$("[id^=container]").append($(".myBoxClass").clone());
The above code will select all the id's starts with container
Fiddle
Use .outerHtml in jquery
$("[id^=container]").append($('#myBox')[0].outerHTML);
DEMO
You can do this my adding the code to a separate page and using .load() JQuery function to load it where you want.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>Projects:</b>
<ol id="new-projects"></ol>
<script>
$( "#something-new" ).load( "/resources/myBox.html #box li" );
</script>
</body>
</html>
clone your html tag.
$("#containerA,#containerB").html($('.myBoxClass').clone());
You could use:
$("[id^=container]").append($(".myBoxClass").clone());
Or
$("[id^=container]").html($(".myBoxClass").clone());
var myBox=$(
'<div class="myBoxClass" id="myBox">'
+'<h1>My Box</h1>'
+'<img src="myPic.png" alt="My Picture" />'
+'<p>Lorem Ipsum...</p>'
+'</div>'
);
Now You got a Jquery Object.
Use this where ever you want.
$('#containerA').append(myBox);
$('#containerB').append(myBox);

Categories