Image not loading in HTML when appended by jQuery - javascript

Image loads correctly in HTML, but not when appended through jQuery.
The project is set up through webpack and images are loaded through file-loader. The code works correctly when directly typed into HTML however, it doesnt work when I attempt to load it through jQuery.
For HTML :
<img src = {require('../images/icon1.png')} className = 'studentIcon' />
For jQuery :
$("#students").append(
$("<div class = 'row'>").append(
$("<div class = 'col-xs-4'>").append(
"<img src = {require('../images/icon1.png')} />"
)
)
)
In HTML the jQuery appended images shows up as:
<img src="{require('../images/icon1.png')}">
with Console error:
icon1.png')%7D:1 GET http://localhost:8080/%7Brequire('../images/icon1.png')%7D 404 (Not Found)
When directly inserted into HTML the images shows correctly, however I have a large number of images which I want to directly attach to some generated code.

You don't need to "nest" many .append() methods like this.
But what you definitely have to do is to concatenate the string (+ sign) with your templating (which runs first), else it's just characters that are part of the string as is.
Here is what you want:
$("#students").append("<div class = 'col-xs-4'><img src = "+{require('../images/icon1.png')}+" /></div>");
And a more "visual/readable" way for the same:
$("#students")
.append("<div class = 'col-xs-4'>"+
"<img src = "+{require('../images/icon1.png')}+" />"+
"</div>");

Would advise the following.
$(function() {
var students = $("#students");
var row = $("<div>", {
class: "row"
}).appendTo(students);
var col = $("<div>", {
class: "col-xs-4"
}).appendTo(row);
$("<img>", {
src: "../images/icon1.png"
}).appendTo(col);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="students">
</div>
This jQuery creates the various HTML Elements as jQuery OIbjects, appends them as needed, and adds them to the DOM. For the Image Source, it is a relative path to the location on the web server.
Hope that helps.

Related

To print a div with the css style

I made a script to print just a div, but when I see the preview, it doesn't "format" the page using the CSS added.
HTML Part:
<center>Do not print this</center>
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
<input type='button' value='Print' onClick='Print()' />
JS part
function Print(){
var corpo = document.getElementById('content').innerHTML;
var a = window.open('','','width=640,height=480');
a.document.open("text/html");
a.document.write("<html><head><link rel=\"stylesheet\" href=\"./style.css\"></head><body><div class=\"print\">");
a.document.write(corpo);
a.document.write("</div></body></html>");
a.document.close();
a.print();
}
A live version: https://codepen.io/Pop1111/pen/Vwabbzd
It looks like it load the css only AFTER.
Any tips?
Your code will create invalid HTML
Try
function Print() {
var corpo = document.getElementById('content').innerHTML;
const html = [];
html.push('<html><head>');
// assuming the first stylesheet on the parent page - use a different selector if not
// or use +location.protocol+'//'+location.host+'/style.css">'
html.push('<link rel="stylesheet" href="' + document.querySelector("link[rel=stylesheet]").href + '">');
html.push('</head><body onload="window.focus(); window.print()"><div>');
html.push(corpo);
html.push('</div></body></html>');
console.log(html)
/* this will not work in the snippet - uncomment on your server
var a = window.open('', '', 'width=640,height=480');
a.document.open("text/html");
a.document.write(html.join(""));
a.document.close();
*/
}
<html>
<head>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<center>Do not print this</center>
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
<input type='button' value='Print' onClick='Print()' />
</body>
</html>
Your new document is unsaved, so does not have your expected path, so the relative reference of the CSS file is not finding the CSS.
To get this to work as expected, you would need to change the CSS reference to absolute reference, or add code to save the new HTML file first.
Is this just how you have tested it, or will your production version function like this as well? (New file, not saved, then print).
You could always inject the actual CSS itself into the head of the new document between style tags, instead of just a reference to the CSS file. Try that.

Summernote text editor not working in simple bootstrap page where html is generated

I added Summernote (a text editor for bootstrap) to a small page I am testing a form generator on. I cannot seem to be able to get the editor in my page at all, even if the examples are simple.
See this simplified jsfiddle I made that works and only has 2 lines.
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-2.2.3.min.js" defer></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="js/bootstrap-checkbox.min.js" defer></script>
<script src="js/bootstrap-filestyle.min.js" defer></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
<script src="js/myJavaScript.js"></script>
</head>
<body onload="addAllElements()">
<br/>
<div class="row" id="mainRow">
</div>
</body>
</html>
And this is my javascript file:
//This function should read a json file and produce the right form
function addAllElements() {
//A test for generated forms (from objects)
for (var i = 0; i < 3; i++) {
addElement({
label: "Some rich text editing :",
tag: "richEditor",
});
}
//We add the styling for checkboxes, file inputs and rich editors
$(':checkbox').checkboxpicker();
$(":file").filestyle({ buttonText: "File", buttonName: "btn-primary", placeholder: "No file" });
$('#richEditor').summernote();
}
//This function add a single element to the form
function addElement() {
//We create the group div (the whole element div)
var newDiv = document.createElement("div");
if(arguments[0].tag !== "richEditor"){
newDiv.className = "form-group col-xs-12 col-sm-6 col-lg-4 col-xl-3";
}else{
newDiv.className = "form-group col-xs-12 col-sm-12 col-lg-12 col-xl-12";
}
//We create and add the label to the div
var newLabel = document.createElement("label");
if(arguments[0].tag == "richEditor"){
newLabel.className = "col-xs-6 col-sm-5 control-label";
}else{
newLabel.className = "col-xs-6 col-sm-5 control-label";
}
newLabel.innerHTML = arguments[0].label;
newDiv.appendChild(newLabel);
//We create and add the input to the div
var inputDiv = document.createElement("div");
if(arguments[0].tag == "richEditor"){
inputDiv.className = "col-xs-6 col-sm-7";
}else{
inputDiv.className = "col-xs-6 col-sm-7";
}
newDiv.appendChild(inputDiv);
switch (arguments[0].tag) {
case "richEditor":
var newInput = document.createElement("div");
newInput.className = "form-control";
newInput.id = "richEditor";
inputDiv.appendChild(newInput);
break;
default:
}
var mainRow = document.getElementById("mainRow");
mainRow.appendChild(newDiv);
}
Would you have an idea on how to correct my code so the editor would actually load in the space I am giving it?
Bootstrap plugins depend on jQuery; they'll fail if it doesn't load first:
Plugin dependencies
Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs. Also note that all plugins depend on jQuery (this means jQuery must be included before the plugin files). Consult our bower.json to see which versions of jQuery are supported.
The defer attribute in your jQuery script loading tag is causing it to load after you call addAllElements in your onload event.
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.

Find a element and append a image

I know how to append a image to a known tag. e.g.
//html
<div class="ImageContainer"></div>
//JS
var image = new Image;
image.src = '/Public/Images/image.png';
image.appendTo($('.ImageContainer'));
but how to find a certain tag(the figure tag here) and append the image?
I could locate the figure tag with '.find()':
var ImageContainer = $('<div><figure></figure></div>').
console.log(ImageContainer.find('figure').html());
but failed to append the image to it:
image.appendTo(ImageContainer.find('figure')); //doesn't work
If you have an image element with an id you can select it like so:
var $image = '<img src="/Public/Images/image.png" />';
Then so find the figure elemnt:
$(ImageContainer).find('figure').append($image);
Try below code.
1) Stored image url in variable name $img.
2) Find the div using class name 'image' ($('.image'))
3) Appended image to div
HTML
<div class="image"> </div>
JS
var $img = '<img src="https://skypeblogs.files.wordpress.com/2013/05/skype-button.png"/>';
$('.image').append($img);
JSFIDDLE DEMO
if you are using jquery, you can just do
var htmlString = '<div><figure><img src="some image src" /></figure></div>';
$('#ImageContainer').html(htmlString);
but if you are wanting to insert the div/figure and image separately, then you'd be best giving it some sort of identifier, i.e.
var htmlString = '<div><figure id="myFig"></figure></div>';
$('#ImageContainer').html(htmlString);
$('#myFig').html('<img src="" />');

adding piece of HTML code using JS based on URL accessed

What I am trying to achieve is if a particular page is loaded in the browser for e.g www.domain.com/page then the following piece of code should be added in the page dynamically using JS (similar to how we load the Google Analytics code)
<div id="something">
<img src="http://domain.com/images/someImage.jpg">
</div>
I am trying to figure the script which will load the above mentioned HTML code (anywhere of the page - www.domain.com/page)
Edit 1:
what I am trying to achieve is when the user goes to www.domain.com/page.html I am calling another page lets say page1.html which should contain the script which insert the HTML code I posted above. So I simply want to insert the function which should be enclosed in the tag inside page1.html. Unfortunately I can not edit www.domain.com/page.html
If you want to PLACE that code anywhere in your page using javascript, you first need to identify that PLACE in DOM Using an "id" attribute. Here's an example:
HTML:
<html>
<body>
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
JS:
var html = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
document.getElementById('target1').innerHTML = html;
document.getElementById('target2').innerHTML = html;
You can try something like this :
$(document).ready(function () {
var url = window.location.href;
$("#something").append("<img src='"+ url +"' />");
});
$(".documentholder").load("code.html");
If you a specific id of something
$(".documentholder").load("code.html #someid");
If you a specific tag and id of something
$(".documentholder").load("code.html #someid");
Here you are,
just change this part if (getFileName() == "js") with if (getFileName() == "page")
I added js because that is what is returning in the code snippet :)
function getFileName() {
var url = document.location.href;
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
url = url.substring(url.lastIndexOf("/") + 1, url.length);
return url;
}
var div = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
if (getFileName() == "js") {
$('body').append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
let's say you save this code in a html-file named something.html
$(".documentholder").load("something.html");
in this case the class "documentholder" is the container you put the code in

Can't update iframe content with jquery

iframe is loaded dynamically into container div inside function.
With cc.text(content); I try to update #code content.
I check changed text in runtime, it's updated but on screen value remains the same.
I am not a javascript pro, so any comments are welcome:
function ShowEditor(content) {
var url = "XmlEditor/Editor.htm";
slHost.css('width', '0%');
jobPlanContainer.css('display', 'block');
frame = $('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" class="frame" frameborder="0" />');
frame.appendTo(jobPlanIFrameContainer);
$(frame).load(function () {
var ifr = frame[0];
var doc = ifr.contentDocument || ifr.contentWindow.document;
var jdoc = $(doc);
var cc = jdoc.contents().find("#code");
// var tst = cc.text();
// alert(tst);
cc.text(content);
});
}
I get the text in commented code, but fail to update #code content.
iframe holds the following html where I omit details inside head and script:
<!doctype html>
<html>
<head></head>
<body>
<form>
<textarea id="code" name="code">some texts</textarea>
</form>
</body>
</html>
Your XML editor doesn't read more than once what's in the textarea.
A simple solution would be to generate in javascript the iframe content with the desired textarea content instead of loading it and then try to change the textarea content.
In fact (depending on the capacities of your XML Editor), you probably can do that directly in a generated text area instead of using a whole iframe to do it.

Categories

Resources