open if bracket in javascript - javascript

I'm trying to execute a HTML code if there is variable in JS, is there something like in PHP, where you can use
<?php
if ($variable == True) { ?>
<img src="image.jpg">
<?php } else { ?>
<img src="image2.jpg">
<?php } ?>
so in JS
<script>
if (variable == true) {
</script>
<img src="image.jpg">
<script>
} else {
</script>
<img src="image2.jpg">
<script>
}
</script>
or it has to been done like this
<script>
if (variable == true) {
$("#element").prepend("<img src='image.jpg'>");
} else {
$("#element").prepend("<img src='image2.jpg'>");
};
</script>
Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/
Thank you :)

Well last one is correct one but you can simplify it:
var src = variable === true ? "image" : "imgage2";
$("#element").prepend('<img src="'+ src +'.jpg">');
Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/
That could be because of dynamically element's creation, you can sort it out with event delegation.
With jQuery:
$('#element').on('click', 'img', function(e){
// put code here
});
With javascript it is little bit different, .querySelectorAll() returns a collection with is array like object, so iteration needs to be there, Collection.forEach(cb) can be used to bind the event:
var imgs = document.querySelectorAll('#element img');
Array.forEach.call(imgs, function(img){
img.addEventListener('click', function(){
// put code here
});
});
And with js all the events are delegated events.

I assume that you want to check if your variable is boolean and you want to check if it is true.
Also i assume that you have several images and you want to prepend new one to them, then you could do:
Create hidden div on the page, Something like this:
<div id="htmlToDomCreator" style="position: absolute; top: 0; left: 0; width: 1px; height: 1px; visibility: hidden;" >
</div>
Inside your javascript code do something like this:
<script>
var htmlToDomCreator = document.getElementById('htmlToDomCreator');
var yourElement = document.getElementById('element');
var htmlTag = "";
if (variable == true) {
htmlTag ="<img src='image.jpg'>";
} else {
htmlTag ="<img src='image2.jpg'>";
}
htmlToDomCreator.innerHTML = htmlTag;
var myImgTag = htmlToDomCreator.firstChild;
if(yourElement.firstChild){
yourElement.insertBefore(myImgTag, yourElement.firstChild);
}else{
yourElement.appendChild(myImgTag);
}
myImgTag.onclick = function() {
// do click stuff here
};
</script>
The idea is that whether you use innerHTML or prepending string with jquery,
you have to take whole innerHTML, prepend string to it and then reinsert
whole content again. As you undoubtedly can see, this "kills" all handlers
added from javascript and you have to reattach them again.
To avoid this, we create dom from string "somewhere else" and then prepend it as a dom child element.

Try this:
<script>
if (variable == true) {
$("#element").attr('src', 'image.jpg');
} else {
$("#element").attr('src', 'image2.jpg');
};
</script>
Comment:This will only change the picture attribute, not the entire <img... /> element. So, events attached to the img element will be preserved.

Related

Toggle image source with jQuery

I want to do something interesting, so for example i have an image on my website and i want to change it when a button is triggered, but then i want to revert it back to the original when the button is clicked again (or add the same img to it) and repeat this all the time when the event is clicked. How can I achieve this ?
Here is my current Jquery but only that works for one time click
$('#menu-btn').on({
'click': function () {
$('#div1').attr('src', 'images/card-light.png');
}
});
Html code
<button id="menu-btn">click me</button>
<img id="div1" src="./images/card-dark.png">
Assets
images/card-dark.png
images/card-light.png
On document load, store the image source in a variable. In our case, it's called prev.
Inside the toggle function, we check whether the source of the image is equal to the source when it was loaded. If it was, we change the source to another image. When the source is changed and we call the toggle function again, we know that the source is different from the previous one, so we revert it back to the original source.
$(document).ready(function() {
var img = $('#img');
var prev = img[0].src;
function toggle(img) {
let src = img.src;
if (src == prev) {
img.src = "https://pbs.twimg.com/profile_images/453956388851445761/8BKnRUXg_400x400.png";
img.height="48";
} else {
img.src = prev;
}
}
$('button').on('click', function() {
toggle(img[0]);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" height="48"></script>
<img id="img" src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<button>Toggle</button>
We can take it a step further by using data attributes to store the two sources so you can easily extend this for multiple images.
$(document).ready(function() {
var img = $('#img');
var prev = img[0].src;
function toggle(i) {
let src = i[0].src;
let dsrc = i.data('switch-with');
if(dsrc==src){
i[0].src=prev;
}else{
i[0].src=dsrc;
i[0].height="48";
}
}
$('button').on('click', function() {
toggle(img);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" height="48"></script>
<img id="img" src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1" data-switch-with="https://pbs.twimg.com/profile_images/453956388851445761/8BKnRUXg_400x400.png">
<button>Toggle</button>

Condition to display image in Javascript

I'm looking for create a small javascript code to display images if their src is valid.
I have to separate the script to the html page for better organisation.
Here is what I did :
HTML
<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png" width="50px" height="50px" alt="" ;>
JavaScript
var thumbnail = document.images.thmb;
if(thumbnail.src)
{
if(thumbnail.onerror)
{
thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}
}
else
{
thumbnail.style.display = "none";
}
Bu it doesn't work, when I empty the src code in HTML, the border of the image still in the page. And if I write a wrong URL, we can't see the image set in the JavaScript.
Here is the JSFiddle to experiment it.
http://jsfiddle.net/gUb8X/
I'm a beginner in JavaScript.
Thank you !
You are too late with the test.
Try this
Live Demo
window.onload=function() {
var thumbContainer = document.getElementById("thmbDiv");
var thumbnail = document.createElement("img");
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}
Now replace your image with a div with id thmbDiv
if you put placeholders or hide all images you want to test, you can get the src from a data attribute.
Live Demo
window.onload=function() {
var imgs = document.images; // or document.getElementsByClassName("testImage");
for (var i=0, n=imgs.length;i<n;i++) {
var theImage = imgs[i];
var src = theImage.getAttribute("data-src");
if (src) {
theImage.onerror=function() {
this.style.display="none"; // or this.parentNode.removeChild(this);
}
}
theImage.src=src;
}
}
A neat inline solution would be this
DEMO http://jsfiddle.net/LstNS/25/
<img src="rando/path" id="image" onerror="this.style.display='none';"/>
jQuery:
You can use an ajax call to check if the image file exists
$.ajax({
url:'http://yourhost/someimage.ext',
type:'HEAD',
error: function()
{
//file does not exist
},
success: function()
{
//file exists do something here
}
});
DEMO http://jsfiddle.net/LstNS/24/
As you can see in the demo, the second image is not loaded and presented as a broken image as it does not exist.
A non jQuery version would be
var img = document.getElementById("myImg");
img.onerror = function () {
this.style.display = "none";
}
Your code now tests for thumbnail.src, which means that you are testing for the existence of an src propery, which always exists for a syntactically valid img element. Then you test for the existence of an onerror event handler, and since there is none, you take a branch that does nothing.
A way that works is to use an onerror attribute in the img element and make it remove the element (or remove it from rendering, but actually removing the element is more logical, and safer):
<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png"
width="50" height="50" alt="" onerror="rm(this)">
<script>
function rm(elem) {
elem.parentNode.removeChild(elem); }
</script>
Unfortunately, you can’t do this so with a loop that traverses through all img elements. If you try that, your code will run only after the image loading has been performed, so it would be too late to try to set onerror handlers on them.
I just found a little trick to make it possible. That doesn't follow the convention but it works. I just use the "alt" image keyword as the "src" keyword, and the JavaScript gives the src equals to alt attribute found in the html.
<img id="thmb" width="50px" height="50px" alt="http://blog.lefigaro.fr/bd/img-sanctuaire.png" ;>
Javascript :
var img = document.getElementById("thmb");
img.src= img.alt;
img.onerror = function () {
img.style.display = "none";
}
http://jsfiddle.net/LstNS/28/
To more, because I have to use a function to return all the final html code, I did this :
display: function (data) {
var pid = data.record.project_id;
var thb = data.record.Thumbnail;
var base_url = "<?php echo base_url('project');?>/";
function checkImg(){
try
{
var thumbnail = document.createElement("img");
thumbnail.src = thb;
} catch(err) {
//
}
if(thumbnail.height > 0){
var result = 'src="' + thb + '"';
}
else
{
var result = 'style="display:none;"';
}
return result;
}
return '<img id="thumbnail" ' + checkImg() + '" width="50px" height="50px" >';
}
I have to thank you for all your answers which permit me to find a good way to do it !
If you have comments to do, don't hesitate ! ;)

append child after the node of the script that made the call

When the call bellow is done the class creates a set of elements (a form) and then I want to append them right after the script that called it.
I have been looking at various similar questions but the best of them simply append it after the last script on the page.
It would work nicely in the head but not the body.
<script type="text/javascript">
new exampleClass();
</script>
You should have some type of unique identification to find and append elements after the script. You can use document.getElementById() if you have id, or document.getElementsByTagName("script") to get script elements and get the required script element and then use appendChild()
Ok, here is the horrible hack mentioned.
HTML
<div>Stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
<script type="text/javascript">
new ExampleClass();
</script>
<div>More stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
Javascript
function noop() {}
function appendAfter(node, newNode) {
if (node.nextSibling) {
node.parentNode.insertBefore(newNode, node.nextSibling);
} else {
node.parentNode.appendChild(newNode);
}
}
function ExampleClass() {
window.addEventListener("load", function () {
var scripts = document.getElementsByTagName("script"),
div = document.createElement("div"),
length = scripts.length,
i = 0,
script;
div.appendChild(document.createTextNode("Inserted"));
while (i < length) {
script = scripts[i];
if (script.firstChild && script.firstChild.nodeValue.indexOf("ExampleClass()") !== -1) {
appendAfter(script, div);
}
i += 1;
}
}, false);
}
On jsfiddle
Based on some of your comments and some other similar I have thought of doing something like this and it seems to work.
// Generate random string we can use as element id
var rs = Math.random().toString(36).substring(2);;
// Document write an empty div with the above string as id
document.write('<div id="' + rs + '"></div>');
// Get the element to use for append
var ip = document.getElementById(rs);
Please feel free to comment if you think it may have a fatal flaw.

I can't get my image slideshow to work using JavaScript

I am trying to create a simple image slideshow type thing with the Javascript code below, but what it is doing is displaying the first image in the webpage with everything else, then after 5 seconds clearing the page and displaying the same image, then again every 5 seconds except it doesn't clear the page anymore.
The JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
The HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
Im not very experienced with Javascript, so thanks in advance for the help.
picNum will always be zero because it is declared inside a function and will set to zero every time the function is called. Even if you fix this, your condition is wrong:
if (picNum = waiPics.length) {
The conditional should be:
if (picNum === waiPics.length) {
The single = sign assigns the length to picNum, then converts to a boolean. The array length is nonzero, so it becomes true value. It then resets to zero every time.
Consider using JSLint to check your code for errors and to suggest improvements. It flagged the issue:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
In fact, after using JSLint on your code and examining its suggestions, I would use something more like this:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
Assigning innerHTML avoids various problems with document.write and also does not require your page to refresh to change slideshow images. Also note other comments.
You need to use the comparison operator ('==') instead of assigning ('=') here:
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {
have a look at this example...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
to get your own slideshow working, copy and paste the following html into any text file and save it as slides.html
you can add any number of <img> elements inside the <div class="slideshow">
enjoy!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>

How to replace all empty <img src=""> on a page with JavaScript on dom loaded?

I need a function, that starts, when the DOM is loaded.
In my HTML Page are several empty Image Tags, like and I want to add an Image-Name into the src-property when everything is loaded to get something like
<img src="blank.jpg">.
Best wishes
Chris
Construction <img src=""> is invalid. Never use it.
It's invalid because empty url means url to current page. But current page is HTML document, not image. Browser can make another query of current page and try to use it as image (see this page).
function replaceSrc()
{
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++)
{
var img = images[i];
if(img.src.length == 0)
{
img.src = 'blank.jpg';
}
}
}
window.onload = replaceSrc;
OR if you want to add more than one handler for the event:
document.addEventListener('load', replaceSrc, false) //W3C
document.attachEvent('onload', replaceSrc); //IE
With jQuery
$(document)
.ready(function() { $('img')
.filter(function(){ return this.src.length == 0 })
.each(function () { this.src = 'blank.jpg'}) });
EDIT:
I realized that you probably want to set the src property before the images load so I changed the code to fire on the document's load event, which happens before the images start loading.
Use jQuery! It's easy.
$('img').attr('src','new-image-name.jpg')
This will set the src attribute of every img tag to 'new-image-name.jpg'.
With jQuery, this would set the src attribute of all img elements with a blank src attribute to "blank.jpg" on page load.
$.ready(function() {
$("img[src='']").attr("src", "blank.jpg");
});
You can use this script.
# Script AddImage.txt
var string pagefile, image, html
# Read in the page file.
cat $pagefile > $html
# Replace all instances of "<img src="blank.jpg">" with the specified image.
while ( { sen -r -c "^<img src=&\>^" $html } > 0 )
sal -r -c "^<img src=&\>^" ("<img src=\""+$image+"\">") $html > null
# Write page back.
echo $html > { echo $pagefile }
Script is in biterscripting. Save the script in file "C:/Scripts/AddImage.txt", run it with this command.
script "C:/Scripts/AddImage.txt" pagefile("/path/to/page.html") image("blank.jpg")
It will replace previous image with "blank.jpg".
With JQuery you can simply solve your problem using following code.
$(function(){
$("img[src='']").attr("src", "blank.jpg");
});
Replace images if null from API data using dom manipulation
const images = document.getElementsByTagName('img');
for(const img of images){
const src = img.getAttribute('src');
if(src === "null" && strGender === "Male"){
img.src = "img/placeholder-male.jpg";
} else if(src === "null" && strGender === "Female"){
img.src = "img/placeholder-female.jpg"
}
}

Categories

Resources