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...
Related
cant get this to work (can I not have JS call from inside list tags?)
Thanks!!!
<head>
<script type="text/javascript">
// Popup window code
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=300,width=400,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
</head>
<body>
<ul>
<li>Helping Kids Who Struggle
</li>
</ul>
..etc
,,but works fine when not in <li>
Thanks!!!
I would advise you to use the jquery library for this solution. In order to use jquery you have to include the jquery files using a CDN or locally. I use a CDN.
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
You can set up a jquery event listener so that once a list item is clicked, an event is executed. For example;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>List Click</title>
<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include the jQuery library -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<ul id="group">
<li id="one">One</li>
<li id="two">Two</li>
<li id="three">Three</li>
<li id="four">Four</li>
<li id="five">Five</li>
</ul>
<script>
$( "#group li" ).bind( "click", function() {
var selected_item = $(this).attr('id');
if(selected_item == "one"){
window.open('helpingkidswhostruggle.html','name','width=600,height=450');
}
});
</script>
</body>
</html>
So to explain the code;
You must assign id attributes to the ul and li tags.
The $( "#group li" ).bind( "click", function() { code looks for the list items with tags of li enclosed in an element with an id of group and assigns a click listener to them so that when they are clicked, a function is called and executed.
The var selected_item = $(this).attr('id'); code uses the attr('id') method to obtain the id of the clicked list item and assign it to variable selected_item. So now this is the use of assigning an id to the list items so that you can identify them.
This if(selected_item == "one"){ code of course checks to see which item has been clicked and the action to take if it has. You can play around with this and see what works for you.
Do not forget to include the jquery files otherwise the code will not work.
Try it and let me know if it helps or if you found a problem
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 )
OK. I feel dumb! I've been trying to do something very simple and yet finding it very difficult to do or to find. All I want to do is:
have the index.html file display.
I want a separate JavaScript file that contains all of my JavaScript code. Completely separated, so I don't have any JavaScript code in my HTML file. I don't want a click event or anything fancy.
I just want the page to display Hello World! onLoad by getting it from a JavaScript function.
BTW: Seems all tutorials either put the JavaScript code in with the HTML or they want to show you how to do something fancy. I've been all over SO to no avail.
The closest I've gotten is listed below. I give up! A little help would be so appreciated.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
</head>
<body>
<script type="text/javascript"></script>
</body>
</html>
script.js:
window.onload = function() {
var result="Hello World!";
return result;
};
if you want to append to body, you can create a text node ( createTextNode() ) and then directly append that to body:
window.onload = function() {
var result = document.createTextNode("Hello World!");
document.querySelector('body').appendChild(result);
};
What you can do is print the text you want to the <body> element when the page loads. Something like this should do the trick:
window.onload = function() {
var result="Hello World!";
document.querySelector('body').innerHTML(result);
};
Or if you had a particular place on your webpage that you wanted to load this text into, you can create an element in your HTML, give it a unique id and reference it in your JavaScript:
<body>
...
<div id="myAwesomeElement"></div>
...
</body>
and in the JavaScript:
window.onload = function() {
var result="Hello World!";
document.querySelector('#myAwesomeElement').innerHTML(result);
};
In your javascript function, you can do something like this:
document.getElementById("divID").innerHTML="Hello World!";
and in your html file create a div or span or something that you want modify(in this case, the inner html content):
<body>
<div id="divID"></div>
</body>
When the function is called, it will find the dom element with the Id of "divID", and the innerHTML will be what you assign the Hello World to. You could modify other properties like css style stuff too.
If you want to grab a hold of a place where to put your file, you need to address it.
Eg.
<body>
<div id="place-for-text"></div>
</body>
And then in your script:
var elem = document.getElementById('place-for-text');
elem.innerHTML = 'Hello world.';
That is about the simplest way to do it in a way you could control some of it.
You could go more fancy and add a DOM element instead:
var elem = document.getElementById('place-for-text');
var text = document.createTextNode('Hello world');
elem.appendChild(text);
Here's a way that hasn't been shown yet.
You can remove the script tag from the head of the file since we want the js file to load up after the rest of the page. Add the script tag with the script.js source to the body.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The script.js file looks like this:
//script. js file
!function () { document.querySelector("body").innerHTML = "hello world"; } ();
The exclamation point and the following () causes the function to run automatically upon load. For more info take a look at this question: What does the exclamation mark do before the function?
EDIT
I should also point out that document.write and .innerHTML are not considered best practice. The simplest reasons are that document.write will rewrite the page and .innerHTML causes the DOM to be parsed again(performance takes a hit) - obviously with this example it doesn't really matter since it's a simple hello world page.
An alternative to document.write and .innerHTML
!function () {
var text = document.createTextNode("Hello World");
document.querySelector("body").appendChild(text);
} ();
It's a bit of a pain, but you can write a function for the process and it's no big deal! The good news is that, with the new ecmascript 6(new JavaScript) you can turn this into a quickly written arrow function like the following:
//script.js
! function() {
var addTextNode = (ele, text) => { //create function addTextNode with 2 arguments
document.querySelector(`${ele}`).appendChild(document.createTextNode(`${text}`));
// ^ Tell the function to add a text node to the specified dom element.
}
addTextNode("body", "Hello World");
}();
Here's a JS Fiddle that also shows you how to append to other elements using the same function.
Hope this helps!
There are multiple ways to ways to solve your problem. The first way only changes your javascript. It uses the document.write() function to write the text to the document.
Here is the new javascript:
window.onload = function() {
document.write("Hello World!");
};
The second way also only changes your javascript. It uses the document.createElement() function to create a p tag and then changes the content inside it then appends it to the body.
Here is the new javascript:
window.onload = function() {
var p=document.createElement("p");
p.innerHTML="Hello World!";
document.body.appendChild(p);
};
window.onload = function() {
document.write('Hello World')
};
Returning from window.onload doesn't do anything productive. You need to call methods on the document to manipulate the page.
Is it possible with javascript/jQuery to create objects on page load (or (document).ready) and then later use them, for example on keyup on an input.
If so, how?
If you put all code in $(document).ready{all code here} then your variables won't go out of scope.
$(document).ready(function(){
var someObject={};
$("selector").click(function(e){
console.log(someObject);
});
});
If you're using onclick in html then I'd advice you to change that and move all JS code to JS file or <script> block (not in your html).
Instead of putting many variables on global scope you can namespace it (if you can't put all code in $(document).ready).
var myApplication = myApplication || {};//if myApplication doesn't exist then create it
myApplication.someObject = {};
Then even if your JS is spread over several files you can still maintain one myApplication object.
As gp mentioned; you can use data to add data to html elements:
$("#somebutton").on("click",function(e){
$(this).data("someObject",{});// you can use e.target instead of this as well
});
Below find a example usage.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write content
<div id="MytextID">My text </div>
<input type="text" id="inputId" name="name">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = $('#MytextID');
$('#inputId').keyup(function(){
alert(x.text());
})
})
</script>
</body>
</html>
First: I am new to javascript so please forgive me if my syntax is novice.
I have been trying to get data in HTML tags using get() in jquery. But no matter how many different variations I try, it just won't work. Can someone please show me what I am doing wrong?
Below is the javascript I am using.
$.get('load.html', function(raw){
var bodyHtml = $(raw).filter('body').html();
var divHtml = $(raw).filter('div').html();
var title = $(raw).filter('title').text();
var tag = $(raw).filter('tag').html();
$('#body').html(bodyHtml);
$('#tag').html(tag);
$('#title').html(title);
$('#result').html(divHtml);
$('#raw').html(raw);
});
Below is the html on the load.html page.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title load.html</title>
</head>
<body>
<div>div 1<tag>divtag</tag></div>
<tag>tag</tag>
</body>
</html>
This is the results once page has run. index.html
<html><head>
<title>index.html</title>
<script type="text/javascript" src="js/jquery/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$.get('load.html', function(raw){
var bodyHtml = $(raw).filter('body').html();
var divHtml = $(raw).filter('div').html();
var title = $(raw).filter('title').text();
var tag = $(raw).filter('tag').html();
$('#body').html(bodyHtml);
$('#tag').html(tag);
$('#title').html(title);
$('#result').html(divHtml);
$('#raw').html(raw);
});
</script>
</head>
<body>
<div id="title">title load.html</div>
<div id="body"></div>
<div id="result">div 1<tag>divtag</tag></div>
<div id="tag">tag</div>
<div id="raw">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>title load.html</title>
<div>div 1<tag>divtag</tag></div>
<tag>tag</tag>
</div>
</body></html>
One thing to note. It looks like the isn't sent back from jquery. Also if there is multiple on the page. Shouldn't this script make it a array (example being )
You need to wrap your $.get() call inside a "document ready" handler - at the moment the DOM elements you're trying to manipulate don't exist at the point you're making the call:
$(document).ready(function() {
// your code here
});
Here is the results. I thought it was the html() tag stripping the body, and head tags out of the variable. When I would do a alert(raw) from a url it would show the full html page. But then when I try and modify that variable, the tags () would disappear. I then thought it was jquery. So I tried a regular expression. Sure enough I got the same exact results. So I am only able to retrieve tags like title, divs, but not the body.
$(document).ready(function() {
$.get('load.html', function(raw){
var matches = raw.match(/<title\b[^>]*>(.*?)<\/title>/gi);
//var matches = matches[0].replace(/(<\/?[^>]+>)/gi, ''); // Strip HTML tags?
alert(matches);
}, "html");
});