inserting content into div with javascript - javascript

dI am succesfully placing text in a div using javascript. However I also want to add images to the text but my javascript method does not seem to accept this. I am using the following code for the text:
document.getElementById("myDiv").innerHTML = "This a bit of text";
See the Fiddle here
Just adding an img tag within the text hasn't worked. Anyone?
Eddy.
And what if I wanted to add the possibility to enlarged the photo using the following script.
<div class="slider jcarousel fancybox" data-jcarousel="true" style="position: relative; width: auto; margin-top: -1px; z-index: 99;">
<ul style="left: 0px; top: 0px; width: 100%;">
<li class="product slide" style="width: auto; border: none;"><a class="zoom first" rel="" href="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300" title=“Test image”><img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300" alt=“Test image“ /></a>
</li>
</ul>
</div>
How would I place this within the text?

You should be able to insert images with innerHtml. Just use '' marks instead of "".
Like this:
document.getElementById("myDiv").innerHTML = 'This a bit of text <img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300" />';
Fiddle

To add images in HTML text you must escape quotes using \ before or use ' instead of " in attributes or string.
If you don't that, then you'll see an error in the browser's console.
This is wrong:
document.getElementById("myDiv").innerHTML="<img src="img.png">"//img.png is outside of the string
Examples:
document.getElementById("myDiv").innerHTML="<img src=\"img.png\"/>"
document.getElementById("myDiv").innerHTML='<img src="img.png">'
document.getElementById("myDiv").innerHTML="<img src='img.png'/>"
How did you try to add the image?

document.getElementById("myDiv").innerHTML = " <img src=' // image path ...'/>This a bit of text";
this way you can add image easily. but please make sure that you are addind image with proper path
OR if it will not work then,
add <img /> tag in HTML. like:
<div id="myDiv">
<img src="..image path..." />
</div>

You shouldn't use innerHTML. This is a better way of doing it:
var myDiv = document.getElementById("myDiv");
myDiv.textContent = "This a bit of text";
var myImg = new Image();
myImg.src = "http://placehold.it/100x50";
myDiv.appendChild(myImg);
<div id="myDiv">
</div>

Related

Removing inline styles from html string

I'm getting data from Wordpress, which contains HTML with inline styles. Before I insert this HTML into my React website, I would like to remove all inline styles. For example, I get something like:
<div style='height: 500px'>
<img style='height: 300px; width: 250px'/>
... more elements with inline styles
</div>
I'm looking for a clean way of doing this because I've tried using other solutions on SO and they use Jquery and other JS methods which would not work since I'm using React to build my website.
You call select all the html tags and using document.querySelectorAll('*') and iterate through each one of them and using removeAttribute, removes style attribute.
const htmlString = `<div style='height: 500px'>
<img style='height: 300px; width: 250px'/>
<p> text</p>
<div style="color: red">Red text</div>
... more elements with inline styles
</div>`;
const htmlNode = document.createElement('div');
htmlNode.innerHTML = htmlString;
htmlNode.querySelectorAll('*').forEach(function(node) {
node.removeAttribute('style');
});
console.log(htmlNode.innerHTML);
You can find all tag in your body then use removeAttribute to remove style attribute.
function remove(){
var allBodyTag = document.body.getElementsByTagName("*");
for (var i = 0; i < allBodyTag.length; i++) {
allBodyTag[i].removeAttribute("style");
}
}
<button onClick="remove()">Remove </button>
<div style='height: 500px'>
This is text
<img style='height: 50px; width: 250px'/>
</div>

Swap image used as background with javascript

This js code below is used in Prestashop to swap the main image with by clicking thumbnails:
$('.js-qv-product-cover').attr('src', $(event.target).data('image-large-src'));
The HTML code for the main image is below:
<div class="product-cover">
<img class="js-qv-product-cover" src="{$product.cover.bySize.ats_large.url}" alt="{$product.cover.legend}" title="{$product.cover.legend}" style="width:100%;" itemprop="image">
</div>
I am trying to use the image as a background and I came up with this code:
<div class="product-cover" style="background-image: url({$product.cover.bySize.ats_large.url});"></div>
In the JS file, I change the 'src' to 'url' but it is not working when I click the thumbnails. What is the right way of doing this so that the main image is swapped as a background?
This is how you change a background image with jquery. In your case, just replace the random urls i used with $(event.target).data('image-large-src') (what should be your own image url.
$('.change').on('click', () => {
$('.container').css("background-image", "url('https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg')");
})
.container {
width: 500px;
height: 200px;
background-image: url('https://images.pexels.com/photos/370799/pexels-photo-370799.jpeg?auto=compress&cs=tinysrgb&h=350')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button class="change">Change</button>
I was able to resolve this by using the code below:
var quickviewDataBgPath = $(event.target).data('image-large-src');
$('.js-qv-product-cover').css('background-image', 'url(' + quickviewDataBgPath + ')' );

How can I configure dynamically appended Ace Editors without causing extra HTML to be generated as a result?

Currently, I can dynamically create a new Ace Editor and append it to a container div as so:
editorsOnScreen++;
$("#container").append(`<div class="questionContainer w-100"
id="questionContainer_` + editorsOnScreen + `" >
<div class="editor" id="editor_` +
editorsOnScreen + `">//Code Here</div>
</div>`);
I can then configure those Ace Editors individually by referencing their ID using the incrementing variable:
var editor = ace.edit("editor_" + editorsOnScreen);
//Perfrom configuration here.
If a user leaves the page, I want to be able to save all of the editors on the screen to reshow them next time, so I use localStorage to save the innerHTML of the container div where they are stored:
localStorage.setItem("divHtml", $("#container").html();
I do this with the intention of then replacing the HTML of the container div with the HTML I previously stored the next time the page is loaded.
This is where the problem comes in. I would expect the HTML saved at the key divHTML to be the following:
<div class="questionContainer w-100" id="questionContainer_` + editorsOnScreen + `" >
<div class="editor" id="editor_` + editorsOnScreen + `">//Code Here</div>
</div>
But, instead, it looks exactly like this (I'm using the three dots because it goes on for lines, and those X's really do come out when I use console.log):
<div class="questionContainer w-100" id="questionContainer_` + editorsOnScreen + `" >
<div class="editor ace_editor ace-vibrant-ink ace_dark" id="editor_2">
<textarea class="ace_text-input" wrap="off" autocorrect="off"
autocapitalize="off" spellcheck="false" style="opacity: 0;">
</textarea><div class="ace_gutter" aria-hidden="true"><div
class="ace_layer ace_gutter-layer ace_folding-enabled"></div><div c
class="ace_gutter-active-line"></div></div><div class="ace_scroller"
style="left: 0px; right: 0px; bottom: 0px;"><div
class="ace_content"><div class="ace_layer ace_print-margin-layer">
<div class="ace_print-margin" style="left: 4px; visibility: hidden;
...
overflow:
visible;">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</div></div></div></div>
I do however find that I get the exactly the results I expect when I don't include any JavaScript or jQuery to configure the editors.
Why would that happen? How can I go about saving the HTML of the container div of which all of the editors are children so that I can easily just replace its HTML with the saved data on the next load of the page?
Thank you.

Place src value form javascript to img tag

I need to put the image source which i am getting perfectly to the <img/> place but i don't know how to.
js:
var aa = document.getElementById("TableImage"+getid).src;
alert(aa);
Result of above js:
Now i want to place this link here:
<!-- Upload Part -->
<div class="ImageUpload">
<label for="FileInput" style="width: 18px; height: 18px; margin-top: -160px; margin-left: 905px;">
<img class="UplaodPic" src="../../img/Upload_Panel.png"/>
</label>
<input name="picture" id="FileInput" type="file" onchange="readURL(this,'Picture2')" style="cursor: pointer; display: none"/>
</div>
I want to replace Upload_Panel.png image with the image in the source aa. Help would be nice.
How about:
$("#FileInput").prev("label").find("img").attr("src", aa);
(Since this was the only element with an ID, I went with that. No idea how many of those classes you have on your page)
var aa = document.getElementById("TableImage"+getid).src;
$('.uplaodPic').attr('src', aa)

Remove border from alt text if image url is not valid

Today is friday and this is a fun question (and a real problem). I am using border around the image but if the image url is not valid, the border appears around the alt text and looks kind of ugly. How to remove it using CSS?
<a href="#">
<img src="http://badsrc.com/blah" style="border:1px solid black" alt="Remove border from this alt text" />
</a>
I don't want to overkill it with server side script or jQuery. Interested in CSS. If no CSS solution is available then other solutions are welcome.
My actual server side script looks like this
If Not String.IsNullOrEmpty(photoURL) Then
photoUrl2="<img src="..." style="border:1px solid #000" alt="BMW for sale">"
end if
jsfiddle
You can use onerror and set the border
<a href="#">
<img src="http://badsrc.com/blah" onerror="this.style.borderWidth=0" style="border:1px solid black" alt="Remove border from this alt text" />
</a>
It would be better to not use inline styles and use classes
jsfiddle
Use .error(), it binds an event handler to the "error" JavaScript event.
$("img").error(function () {
$(this).css('border', 'none');
})
DEMO
<a href="#">
<img id="myImage" src="http://badsrc.com/blah" style="border:1px solid black" alt="Remove border from this alt text" />
</a>
<script>
var image = document.getElementById('myImage'); // or select based on classes
image.onerror = function(){
// image not found or change src like this as default image:
image.style.border = "none";
};
</script>
here is your solution with javascript.
Since you are setting it via server side, the correct thing to fix this on the server side, not in CSS or JavaScript. All you have to do is change your code to this:
photoUrl2 = String.Format("<img src='...' style='border:{0}' alt='BMW for sale' />",
If(String.IsNullOrEmpty(photoURL),
"none",
"1px solid #000"))
I know it's an old question but here is CSS only solution using pseudo elements
img:after {
content: attr(alt);
position: absolute;
z-index: 2;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #fff;
}
<img src="//placehold.foo/200x200" alt="Remove border from this alt text" />

Categories