jQuery .html() method syntax - javascript

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 )

Related

I'm trying to get the innerHTML of all <h2> tags and set that as their individual IDs but I'm not sure how to go about it

Basically I have a bunch of <h2> tags and without going into detail, I can't manually assign them IDs. So I THINK I could use .innerhtml to somehow get the <h2> text and assign that as IDs for them but I'm not sure how to get started.
Is this even possible?
The html would look something like this:
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
As the comments have said, you should avoid using innerHTML unless you are sure you want the HTML content of the element - Using innerText instead will make sure you only receive the plaintext
You can use querySelectorAll to get all of the h2 elements in an HTMLCollection
You can then simply loop over this and update the property directly by using:
ele.id = ele.innerText;
Or you can make use of setAttribute like this:
ele.setAttribute('id', ele.innerText);
.
You might also want to use .toLowerCase() after the innerHTML, just to have a more standard ID styling
document.querySelectorAll('h2').forEach((ele) => {
ele.id = ele.innerText;
});
console.log(document.getElementById('History').innerText);
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
You will want to use the DOM to find all the h2 elements and process accordingly:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
var h2s = document.querySelectorAll('h2');
h2s.forEach(function(h2Element) {
h2Element.id = h2Element.innerText;
});
</script>
</body>
</html>

jQuery append template?

I'm trying to insert some template with jQuery and get two different results when I'm using:
a)
var $template = $("#productTemplate").html();
b)
var $template = $($("#productTemplate").html());
If I use a) case I can add template many times, if I use b) I can add template only one time.
So what is the difference?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="style.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="but">
Click
</div>
<script id='productTemplate' type='text/template'>
<div class="product">
<h1>H1</h1>
</div>
</script>
</body>
</html>
main.js
$(document).ready(function(){
var $template = $($("#productTemplate").html());
$(".showForm").on("click",function() {
$("body").append($template);
});
});
In (a) $template is a string, and .append($template) will always create a new DOM fragment, based on the string, before appending.
In (b) $template is an object, because $(HTML_String) returns jQuery, and .append($template) will always use the same object - re-appending it will move it around in the DOM. To reuse $template, you need to explicitly .clone() it before appending.
"My guess": Probably when you load your $template object outsite the click handler, jQuery identifies you are trying to append the same jQuery objet, and then jQuery doesn't append. If you load your variable again, it works:
$(document).ready(function() {
$(".showForm").on("click", function() {
var $template = $($("#productTemplate").html()); //inside the click handler works
$("body").append($template);
});
});
Plunker: https://plnkr.co/edit/L19RGOKeQXYYkvOuBbX7?p=preview
EDIT:
The difference between the two options is that the b) you can manipulate like an already DOM element, i.e., you can do something like:
$template.find("#my_hidden_id").val("12");
$template.find("#another_div").append("<p>Another html</p>");
and then append your new custom template...

js hook on html load process in browser

Imagine I have following html with many items:
<html><body>
<img src=http://host.com/pic1.jpg>
<img src=http://host.com/pic1.jpg>
<img src=http://host.com/pic1.jpg>
</html></body>
Site owner adds some script to the page without other modifications:
<script>
var some_super_function = ... // what can i put here?
some_super_function('host.com','ghost.com');
</script>
and during loading of this html, host.com is replaced with hgost.com, so images are loaded from another server, as if the urls were:
<html><body>
<img src=http://ghost.com/pic1.jpg>
<img src=http://ghost.com/pic1.jpg>
<img src=http://ghost.com/pic1.jpg>
</html></body>
I guess selecting $('img') and tuning .attr() is not a good idea, because this may work only after page has loaded and I don't want the browser to reference host.com at all.
I guess angularJS is doing something like that, isn't it?
Is this possible?
Thanks.
Tested in firefox:
<body>
<script>
document.write('<!--');
var body = null;
setTimeout(function() {
body = document.body.innerHTML
console.log(body)
}, 0)
</script>
Now you can extract page contents from body variable, do with them whatever you wish and then put into page (with jQuery('body').html(...) for example).
I don't know if it would work if there were comments in the page. There are other ways to stop page from loading. Something like document.write('<script>');. I also tried document.write('<style>'); in firefox, also works.
You can use angular ng-src and {{}} syntax to bind your img domain:
var superFn = function(){ $('img').attr('src','ghost'); }
superFn();
angular.module('myApp',[]).controller('myCtrl',myCtrl);
function myCtrl($scope){
$scope.domain = "a3.mzstatic.com";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<img ng-src="http://{{domain}}/us/r30/Purple69/v4/d5/9e/6d/d59e6dfa-2176-7bc1-20a8-d3a1316c7bb8/icon100x100.png" >
<img ng-src="http://{{domain}}/us/r30/Purple69/v4/d5/9e/6d/d59e6dfa-2176-7bc1-20a8-d3a1316c7bb8/icon100x100.png" >
<img ng-src="http://{{domain}}/us/r30/Purple69/v4/d5/9e/6d/d59e6dfa-2176-7bc1-20a8-d3a1316c7bb8/icon100x100.png" >
</div>
I guess I know what you need. You need to define a base, and manipulate it to serve your needs. Like:
<script type="text/javascript">
document.write("<base href='http://yourimageurl.com/' />");
</script>
You must use this code before body tag.
How can you set your image urls? This way you have to mirror file names in order to make it work. And only relative url's will work.
Can you use CSS to hide the images initially, wait until the document is ready, then change the images and display them in JS?
CSS
img {
display: hide;
}
JS
$(document).ready( function() {
// ... selecting $('img') and tuning .attr() as mentioned in question
// Show the images
$('img').show();
}
I guess angularJS is doing something like that, isn't it?
No, angular use ng-src but for that you need to change the html
Is this possible?
I don't think it's possible to do reliably, from the client side without changing the html. One issue is when the document is loading, the browser will fetch images as soon as browser hits the image src element, even if you can execute a script before that, since document is not loaded script does not have access to the element.
May be you could kick off a window.setInterval function to check for elements and change sources, still it's not going to be a good approach.
In pure Js
you can do :
<!DOCTYPE html>
<html>
<head>
<script>
some_super_function = function(orig, alt)
{
Array.prototype.forEach.call(document.querySelectorAll("img[src*='"+orig+"']"), function(img)
{
var src = img.src;
var host = src.replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
img.src = "http://"+src.replace(host, alt);
});
}
</script>
</head>
<body>
<img id="ol" src="http://www.intertools.net/lib/media/img/selector.png">
<img id="io" src="http://www.intertools.net/lib/media/img/selector.png">
<script>
// callable anywhere
some_super_function("www.intertools.net", "en.intertools.net");
</script>
</body>
</html>
To avoid caching, you can even use (assuming you are using html5)
<html manifest="manifest.appcache">
If I not mistaken is it your requirement.
var some_super_function = function(old_host,new_host)
{
$('img').each( function() {
var newSrc;
newSrc = $(this).attr('src').replace(old_host, new_host);
$(this).attr('src',newSrc);
console.log($(this).attr('src'));
});
}
some_super_function('host.com','ghost.com');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<img src="http://host.com/pic1.jpg" alt="pic1"/><br/>
<img src="http://host.com/pic2.jpg" alt="pic2"/><br/>
<img src="http://host.com/pic3.jpg" alt="pic3"/><br/>
JsFiddle Demo

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.

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

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");

Categories