Showing image in webpage using knockout binding - javascript

this is my html code
<div class="fileupload fileupload-new" data-provides="fileupload">
<div data-bind="if: imgSrc">
<div class="fileupload-new thumbnail" style="width: 150px; height: 150px;"></div>
</div>
<div data-bind="ifnot: imgSrc">
<div class="fileupload-new thumbnail" style="width: 150px; height: 150px;"><img src="${pageContext.request.contextPath}/resources/ui_resources/img/profile_pic.png" /></div>
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 150px; max-height: 150px; line-height: 20px;"></div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" data-bind=" file: imgFile, fileObjectURL: imgSrc"/></span>
Remove
</div>
</div>
and I am binding like
var Patientp = function () {
this.id = ko.observable(idValue);
this.name = ko.observable(nameValue);
this.address = ko.observable(addressValue);
this.gender = ko.observable(genderValue);
//this.consultant= ko.observableArray(consultantArrValue);
this.username = ko.observable(usernameValue);
this.password = ko.observable(passwordValue);
this.email = ko.observable(emailValue);
this.mobile = ko.observable(mobileValue);
this.imgFile = ko.observable(imgFileValue);
this.imgSrc = ko.observable(imgSrcValue);
this.imagePath=ko.observable(imagePathValue);
this.userid=ko.observable(useridValue);
//this.consultant= ko.observableArray(consultantArrValue);
this.consultant= ko.observable(consultantValue);
}
idValue = '4';
useridValue = '6';
nameValue = 'fri1';
addressValue = 'fri1';
genderValue = 'Male';
mobileValue = '1234567890';
//these fields are not available
usernameValue = 'fri1';
passwordValue = '';
emailValue = 'fri1#fri1.com';
imgFileValue = 'fri1';
imgSrcValue='http://socialtv.s3.amazonaws.com/EmzSqEmzSq.jpg'
//imgSrcValue = 'http://socialtv.s3.amazonaws.com/EmzSqEmzSq.jpg';
imagePathValue = 'fri1';
//consultantArrValue = null;//'fri1';
consultantValue="d1";
//var doc={};
var projectUrl=$('#projectUrl').val();
and this is the fiddle
The problem is the actual image is not showing the image area instead a blank div area is showing as shown in the screenshot
Can anybody please tell me how to show the image?

Do you mean that you want to add <img data-bind="attr: {'src': imgSrcValue}" /> inside thumbnail div, like:
<div data-bind="if: imgSrc">
<div class="fileupload-new thumbnail" style="width: 150px; height: 150px;">
<img data-bind="attr: {'src': imgSrcValue}" />
</div>
</div>

You are setting the src without using a binding, so it wont work properly.
You do it like this:
Js
var model = function () {
this.imgPath = ko.observable("http://jsfiddle.net/img/logo.png");
}
ko.applyBindings(model);
Html
<img data-bind="attr:{src: imgPath}"></img>
(Fiddle)

Related

Javascript DOM onclick not working for img src

I can't understand why the functions are not being called or if not that why the background image isn't being changed?
script tags:
<script type="text/javascript" >
function start()
{
document.body.style.backgroundImage = "url('sothback.png')";
document.body.style.backgroundSize = "100%";
document.body.style.backgroundRepeat = "repeat-y";
}
window.onload = start;
function cartman()
{
document.getElementById("image").style.src = "cartman.png";
}
function kenny()
{
document.getElementById("image").style.src = "kenny.png";
}
</script>
body:
<body>
<div style="width: 100%; height: 700px;">
<button onclick="kenny()">Kenny</button>
<button onclick="cartman()">cartman</button>
<div style="height: 400px;"></div>
<center><img src="kenny.png" alt="img" id="image" ></center>
</div>
</body>
Try with this
function cartman() {
document.getElementById("image").setAttribute('src','cartman.png');
}
function kenny() {
document.getElementById("image").setAttribute('src','kenny.png');
}
function start()
{
document.body.style.backgroundImage = "url('sothback.png')";
document.body.style.backgroundSize = "100%";
document.body.style.backgroundRepeat = "repeat-y";
}
window.onload = start;
function cartman()
{
document.getElementById("image").setAttribute('src',"cartman.png");
document.getElementById("image").setAttribute('alt',"Image of cartman");
}
function kenny()
{
document.getElementById("image").setAttribute('src',"kenny.png");
document.getElementById("image").setAttribute('alt',"Image of kenny");
}
</script>
<div style="width: 100%; height: 700px;">
<button onclick="kenny()">Kenny</button>
<button onclick="cartman()">cartman</button>
<div style="height: 400px;"></div>
<center><img src="kenny.png" alt="img" id="image" ></center>
</div>
Update the style.src to setAttribute.
Also consider setting alt tags and title for accessibility and screen readers.

how to onclick change image between 3 images

Hi I am new to javascript and I want to change the image when I click the image. I can do this with 2 images, how do I do this with 3 images?
function change() {
var image = document.getElementById('changeimg');
console.log(image)
switch (image) {
case "image2":
document.getElementById('changeimg').src = "css3.png";
break;
default:
case "image3":
document.getElementById('changeimg').src = "javascript.png";
}
}
<h1 align="center">Change Image</h1>
<br>
<div class="container" align="center">
<img src="html5.png" style="height: 500px; width: 500px" id="changeimg" onclick="change()">
</div>
Just replace your real image name in the imgArr
var img = 0;
var imgArr = ["img1.png", "img2.png", "img3.png"]
function change() {
var image = document.getElementById('changeimg');
console.log("Current image => ", imgArr[img])
document.getElementById('changeimg').src = imgArr[img];
if (img == 2) img = 0;
else
img++;
}
<h1 align="center">Change Image</h1>
<br>
<div class="container" align="center">
<img src="html5.png" style="height: 500px; width: 500px" id="changeimg" onclick="change()">
</div>

JS upload cropper with two instances

I'm trying to upload a second img to the cropper that populates the second .img-result. The cropper should populae whatever was uploaded, and then when the save btn is pressed, the .img-result is updated.
I added the attribute data-up but I'm not sure how to call it in the JS.
// vars
var result = document.querySelector('.result'),
img_result = document.querySelector('.img-result'),
img_w = document.querySelector('.img-w'),
img_h = document.querySelector('.img-h'),
options = document.querySelector('.options'),
save = document.querySelector('.save'),
cropped = document.querySelector('.cropped'),
upload = document.querySelector('.file'),
cropper = '';
// on change show image with crop options
upload.addEventListener('change', function(e) {
if (e.target.files.length) {
// start file reader
var reader = new FileReader();
reader.onload = function(e) {
if (e.target.result) {
// create new image
var img = document.createElement('img');
img.id = 'image';
img.src = e.target.result;
// clean result before
result.innerHTML = '';
// append new image
result.appendChild(img);
// init cropper
cropper = new Cropper(img);
}
};
reader.readAsDataURL(e.target.files[0]);
}
});
// save on click
save.addEventListener('click', function(e) {
e.preventDefault();
// get result to data uri
var imgSrc = cropper.getCroppedCanvas({
width: img_w.value // input value
}).toDataURL();
// show image cropped
cropped.src = imgSrc;
});
.img-result {
border: 2px solid;
width: 50px;
height: 50px;
}
.img-result img {
max-height: 100%;
max-width: 100%;
}
.page {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
height: 100%;
}
.result {
display: flex;
}
.box {
padding: 0.5em;
width: 100%;
margin: 0.5em;
}
.box-2 {
padding: 0.5em;
width: calc(100%/2 - 1em);
}
.img-w {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main class="page">
<div class="box">
<div class="options">
<input type="number" class="img-w" value="300" min="100" max="1200" />
</div>
<button class="btn save">Save</button>
</div>
<div class="box">
<input class="file" type="file" id="file-input" data-up="1">
</div>
<div class="box">
<input class="file" type="file" id="file-input" data-up="2">
</div>
<div class="box-2">
<div class="result"></div>
</div>
<div class="result">
<div class="box-2 img-result">
<img class="cropped" src="" alt="" data-up="1">
</div>
<div class="box-2 img-result">
<img class="cropped" src="" alt="" data-up="2">
</div>
</div>
</main>
First of all, as I mentioned in comments. Id must be for each element of your DOM. So, you better change id="file-input" to id="file-input1" and so on.
And It looks like you want to get the attribute value data-up when save function called,
You can do that in this way
save.addEventListener('click', function(e) {
e.preventDefault();
// get result to data uri
document.getElementById('file-input1).getAttribute('data-up')
....

setInterval() not working with src linked images in HTML

New coder - 1st question here. I'm doing first free code camp project, but question is about a unrequired flourish I just want to add and learn about, it's not needed for project. I want the album covers I've linked in HTML to change every x seconds. But nothing happens yet. Images just stay static. Thanks
<h2> Discography </h2>
<div class="row">
<div id="album" class="col-lg-8">
<div class="albums" id="album 0"> <span><img src="https://upload.wikimedia.org/wikipedia/en/b/b6/Elliottsmithromancandle.jpeg" alt="1994" class="img-responsive"></span></div>
<div class="albums" id="album 1"> <span><img src="https://upload.wikimedia.org/wikipedia/en/e/e3/Elliott_Smith_%28album%29.jpg" alt="1995" class="img-responsive"></span></div>
<div class="albums" id="album 2"> <span><img src="https://upload.wikimedia.org/wikipedia/en/f/fd/Elliottsmitheitheror55.jpg" alt="1997" class="img-responsive"></span></div>
<div class="albums" id="album 3"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/3/…albumcover.jpg/330px-ElliottsmithXOalbumcover.jpg" alt="1998" class="img-responsive"></span></div>
<div class="albums" id="album 4"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/…_cover.jpg/330px-Elliott_smith_figure_8_cover.jpg" alt="2000" class="img-responsive"></span></div>
<div class="albums" id="album 5"> <span><img src="https://upload.wikimedia.org/wikipedia/en/8/8c/Elliott_smith_from_a_basement_on_the_hill_cover.jpg" alt="2004" class="img-responsive"></span></div>
<div class="albums" id="album 6"> <span><img src="https://upload.wikimedia.org/wikipedia/en/4/4e/New_Moon_%28Elliott_Smith_album%29_cover.jpg" alt="2007" class="img-responsive"></span></div>
</div>
and the javascript code
//Change album cover after 5 seconds - continous loop//
var Discography = document.getElementById("album");
var disc = ["album 0", "album 1", "album 2", "album 3", "album 4", "album 5", "album 6"];
var counter = 0;
function changeDisc() {
if (counter >= disc.length) {
counter = 0;
}
Discography.setAttribute =disc[counter];
counter++;
}
var myCounter = setInterval(changeDisc, 6000);
Discography.onClick = function() {
clearInterval(Disography);
Discography.innerHTML = "Counter stopped";
};
You aren't actually setting the attribute. You are actually removing the setAttribute method and replacing it with the url. I think you want this:
function changeDisc() {
if (counter >= disc.length) {
counter = 0;
}
Discography.setAttribute('src', disc[counter]);
counter++;
}
I managed to get your code working. I don't know if this is what you wanted, but I hope it helped you.
Assign Attributes
Discography.setAttribute = disc[counter];
Should be
Discography.setAttribute("src", discs[counter]);
Bind EventHandlers
Discography.onClick = function() {
Should be
Discography.addEventListener("click", function () {
Wrong Element
You tried to assign the src attribute to the <div id="album" class="col-lg-8"> which is a div and it does not have that attribute.
To fix this I added all possible album images to a Array and this will be assigned to a single <img /> to get this working.
Note that I modified some naming conventions, which I do prefer.
My Solution
var discs = [
"https://upload.wikimedia.org/wikipedia/en/b/b6/Elliottsmithromancandle.jpeg",
"https://upload.wikimedia.org/wikipedia/en/e/e3/Elliott_Smith_%28album%29.jpg",
"https://upload.wikimedia.org/wikipedia/en/f/fd/Elliottsmitheitheror55.jpg",
"https://upload.wikimedia.org/wikipedia/en/thumb/3/…albumcover.jpg/330px-ElliottsmithXOalbumcover.jpg",
"https://upload.wikimedia.org/wikipedia/en/thumb/a/…_cover.jpg/330px-Elliott_smith_figure_8_cover.jpg",
"https://upload.wikimedia.org/wikipedia/en/8/8c/Elliott_smith_from_a_basement_on_the_hill_cover.jpg" ,
"https://upload.wikimedia.org/wikipedia/en/4/4e/New_Moon_%28Elliott_Smith_album%29_cover.jpg",
];
var counter = 0;
var discography = document.getElementById("album");
function moveToNextDisc() {
if (counter >= discs.length) {
counter = 0;
}
discography.setAttribute("src", discs[counter]);
counter++;
}
var interval = setInterval(moveToNextDisc, 1000);
discography.addEventListener("click", function () {
clearInterval(interval);
discography.innerHTML = "Counter stopped";
});
<h2>Discography</h2>
<div class="row">
<div class="col-lg-8">
<div class="albums">
<span>
<img id="album" alt="1994" class="img-responsive">
</span>
</div>
</div>
</div>
for learning purpose, you are developing a component that:
changes cover every track change
stops when the user pauses
Javascript should be used for business logic and html/css as a view reflection of the state of the component.
So we need for an Object which has at least three methods:
public play starts the player
public pause pauses the player
private _loop iterates through the tracks
and for a Controller which controls the html view.
function Player(element, interval) {
this.element = element;
this.tracks = element.querySelectorAll('.albums');
this.currentTrack = null;
this.isPlaying = false;
this._timeout = null;
this.interval = Number(interval) || 2000;
}
Player.prototype.pause = function() {
window.clearTimeout(this._timeout);
this.isPlaying = false;
return this;
};
Player.prototype.play = function() {
this.isPlaying = true;
return this._loop();
};
Player.prototype._loop = function() {
var self = this;
self._timeout = window.setTimeout(function() {
var track;
if(self.currentTrack) {
track = self.currentTrack.nextElementSibling;
self.currentTrack.style.opacity = 0;
}
if(!track) {
track = self.tracks[0];
}
track.style.opacity = 1;
self.currentTrack = track;
return self._loop();
}, self.interval);
return this;
}
/** VIEW CTRL **/
function PlayerCtrl() {
var element = document.querySelector('#album');
var player = new Player(element, 3000);
var play = document.querySelector('#Play');
var pause = document.querySelector('#Pause');
play.onclick = function() {
return player.isPlaying || player.play();
};
pause.onclick = function() {
return player.isPlaying && player.pause();
};
player.play();
}
document.addEventListener('DOMContentLoaded', PlayerCtrl);
#album {
width: 300px;
height: 300px;
margin: 10px auto;
overflow: hidden;
background: lightcoral;
position: relative;
border: 3px dotted #333;
}
.albums {
transition: 450ms opacity linear;
opacity: 0;
position: absolute;
top: 0;
left: 0;
}
.albums img { max-width: 100%; }
<button id="Play">Play</button>
<button id="Pause">Pause</button>
<hr />
<h2> Discography </h2>
<div class="row">
<div id="album" class="col-lg-8">
<div class="albums" id="album 0"> <span><img src="https://upload.wikimedia.org/wikipedia/en/b/b6/Elliottsmithromancandle.jpeg" alt="1994" class="img-responsive"></span></div>
<div class="albums" id="album 1"> <span><img src="https://upload.wikimedia.org/wikipedia/en/e/e3/Elliott_Smith_%28album%29.jpg" alt="1995" class="img-responsive"></span></div>
<div class="albums" id="album 2"> <span><img src="https://upload.wikimedia.org/wikipedia/en/f/fd/Elliottsmitheitheror55.jpg" alt="1997" class="img-responsive"></span></div>
<div class="albums" id="album 3"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/3/…albumcover.jpg/330px-ElliottsmithXOalbumcover.jpg" alt="1998" class="img-responsive"></span></div>
<div class="albums" id="album 4"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/…_cover.jpg/330px-Elliott_smith_figure_8_cover.jpg" alt="2000" class="img-responsive"></span></div>
<div class="albums" id="album 5"> <span><img src="https://upload.wikimedia.org/wikipedia/en/8/8c/Elliott_smith_from_a_basement_on_the_hill_cover.jpg" alt="2004" class="img-responsive"></span></div>
<div class="albums" id="album 6"> <span><img src="https://upload.wikimedia.org/wikipedia/en/4/4e/New_Moon_%28Elliott_Smith_album%29_cover.jpg" alt="2007" class="img-responsive"></span></div>
</div>

Hyperlink downloads whatever that img src is

Alright i can't really seem to find anything regarding EXACTLY what i'm doing.
Anyways i need to set a hyperlink to download an image. That image has an id already.
Everytime the user displays an image, the download link will download that image they have entered.
When you run the code, enter 255812 for image code.
function myFunction() {
var x = document.getElementById("imagetxt").value;
var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";
// Creating an image
var img = new Image();
// Defining the function if image loads successfully.
img.onload = function() {
document.getElementById("image1").src = y;
};
//Defining the function if image fails to load.
img.onerror = function() {
alert("Image not found");
};
img.src = y;
}
<body align="center">
<div>
<img src="http://i.imgur.com/dXo8Fxp.png" width="20%" height="20%">
</div>
<div>
<img src="http://i.imgur.com/jCOLCiU.png" width="8%" height="8%">
</div>
<div>
<input id="imagetxt" size="6" type="text" value="">
</div>
<div>
<input id="btn1" type="button" value="Display" onclick="myFunction()" style="top: 5px; position: relative;">
</div>
<div>
<img id="image1" src="" width="30%" height="30%" style="top: 10px; position: relative;">
</div>
DOWNLOAD THIS
Get rid of the onclick on the anchor tag
<a href="#" id="imageDL" download>DOWNLOAD THIS</a>
Set the anchor's href in the img.onload
img.onload = function() {
document.getElementById("image1").src = y;
document.getElementById("imageDL").href = y;
};
Add this to the end of myFunction
document.getElementById("imageDL").href = y;
function myFunction() {
var x = document.getElementById("imagetxt").value;
var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";
// Creating an image
var img = new Image();
// Defining the function if image loads successfully.
img.onload = function() {
document.getElementById("image1").src = y;
};
//Defining the function if image fails to load.
img.onerror = function() {
alert("Image not found");
};
img.src = y;
document.getElementById("imageDL").href = y;
}
<body align="center">
<div>
<img src="http://i.imgur.com/dXo8Fxp.png" width="20%" height="20%">
</div>
<div>
<img src="http://i.imgur.com/jCOLCiU.png" width="8%" height="8%">
</div>
<div>
<input id="imagetxt" size="6" type="text" value="">
</div>
<div>
<input id="btn1" type="button" value="Display" onclick="myFunction()" style="top: 5px; position: relative;">
</div>
<div>
<img id="image1" src="" width="30%" height="30%" style="top: 10px; position: relative;">
</div>
DOWNLOAD THIS

Categories

Resources