Send Javascript Variable to HTML Img Source - javascript

I am utilizing a piece of JavaScript code to change image sources on a WordPress website (leveraging the Elementor editor), which is based on a button click updating the URL with a specific string. For example, this process would yield the following:
Before Click: www.website.com/acoolpage/
After Click: www.website.com/acoolpage/?picture=ws10m
This HTML constructor creates the dimension of the image, but does not update the image source with the desired result after the button click, when the URL switches to www.website.com/acoolpage/?picture=ws10m. What additional steps and/or edits are required? Thanks!
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('?picture=')
const pictureUrl =
switch (pictureParam) {
case 'ws10m':
return 'https://www.website.com/graphics/image_ws10m.png'
break
default:
return 'https://www.website.com/graphics/image_t2m.png'
break
}
<body>
<img src=pictureURL alt="Test" width="1920" height="1080">
</body>

Wrong call to get
image source is not assigned anywhere, img src=pictureURL is wishful thinking
switch does not return a value
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.
You likely meant to do this
window.addEventListener("DOMContentLoaded", function() {
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture')
document.getElementById("img").src = `https://www.website.com/graphics/image_${pictureParam === 'ws10m' ? 'ws10m.png' : 't2m.png'}`
})
<img src="" id="img" alt="Test" width="1920" height="1080">
Alternative for more versions
window.addEventListener("DOMContentLoaded", function() {
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture');
document.getElementById("img").src = `https://www.website.com/graphics/image_${pictureParam ? pictureParam : 'default.png'}`
})
<img src="" id="img" alt="Test" width="1920" height="1080">

You can use the locationchange event to detect if the URL has been changed by a button click.
The code is as follows :
const obj = document.getElementById('#IDFromDOM');
function updateImage(){
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture')
const pictureUrl = pictureParam === 'ws10m' ? 'https://www.website.com/graphics/image_ws10m.png' : 'https://www.website.com/graphics/image_t2m.png'
obj.src = pictureUrl;
}
window.addEventListener('locationchange', updateImage);
updateImage(); //Fire a first time on page load

Related

Python FastAPI: Returned gif image is not animating

Below is my Python and Html code:-
Python:
#app.get('/', status_code=200)
async def upload_file(file: UploadFile = File(...)):
error_img = Image.open('templates/crying.gif')
byte_io = BytesIO()
error_img.save(byte_io, 'png')
byte_io.seek(0)
return StreamingResponse(byte_io, media_type='image/gif')
HTML:
<img src="" id="img-maze" alt="this is photo" style="display: none;" />
function goBuster(file) {
fetch('/', {
method: 'GET',
body: data
})
.then(response => response.blob())
.then(image => {
var outside = URL.createObjectURL(image);
var mazeimg = document.getElementById("img-maze");
mazeimg.onload = () => {
URL.revokeObjectURL(mazeimg.src);
}
mazeimg.setAttribute('src', outside);
mazeimg.setAttribute('style', 'display:inline-block');
})
}
The image is not animating, I checked the generated html and found:
<img src="blob:http://127.0.0.1:8000/ee2bda53-92ac-466f-afa5-e6e34fa3d341" id="img-maze" alt="this is photo" style="display:inline-block">
So the img src is using blob, I guess this is the reason why the gif is not animating, but I have no idea how to fix it.
Update 1
Now I have updated my code to:
with open('templates/crying.gif', 'rb') as f:
img_raw = f.read()
byte_io = BytesIO()
byte_io.write(img_raw)
byte_io.seek(0)
return StreamingResponse(byte_io, media_type='image/gif')
The generated HTML looks same:
<img src="blob:http://127.0.0.1:8000/c3ad0683-3971-4444-bf20-2c9cd5eedc3d" id="img-maze" alt="this is maze photo" style="display:inline-block">
but it gets worse, the image is not even showing up.
error_img.save(byte_io, 'png')
You're converting this image to png. PNG doesn't support animation.
I think you can use:
#app.get('/', status_code=200)
async def upload_file(file: UploadFile = File(...)):
with open('templates/crying.gif', 'rb') as f:
img_raw = f.read()
byte_io = BytesIO(img_raw)
return StreamingResponse(byte_io, media_type='image/gif')
(Posted solution on behalf of the question author, in order to post it in the answer space).
I fixed the problem by:
using the code provided by #VadSim,
change wb to rb
Notice: if you ran the program and then changed wb to rb, the code would have destroyed the original gif image to be a 0 bytes image. This is why it was not working at first.
Now, I have the gif working in html :)

Split image path gotten from database and append to src

I have multiple image paths saved into the database in the same column. The image is saved in this sample in the database:
Two images are not uploaded every time (the highlighted is the multiple image upload example separated by comma). I am using Nodejs and am getting the image data with foreach on the ejs side (data is the output of the select statement on the index.ejs side
index.js
router.get('/homes', function (req, res, next) {
db.query("SELECT * FROM stocks", function (err, rs) {
if (err) {
console.log(err);
}
else {
res.render('homes', {data:rs})
}
});
});
<% data.forEach(function(item) { %>
<input type="hidden" id="desc" value="<%= item.image %>" />
<img id="pic1" class="pic-1" src = "" alt="image" >
<% }); %>
item.image value (input string you are getting from $('#desc').val()). It is just string format of the image path as the loop occurs.
MyImage-1591506118979.png
MyImage-1591507932201.jpg
photos-1591548210637.jpg,photos-1591548210640.png
MyImage-1591494888039.png
MyImage-1591505437596.jpg
MyImage-1591084895899.jpg
MyImage-1591085173153.jpg
MyImage-1590905192772.JPG
I am saving the image on my localhost server. I am doing the split and wanting to append the src in the script tag with the code below:
<script>
var desc = $('#desc').val();
var temp = new Array();
temp = desc.split(",");
var container = document.getElementById("container");
temp.forEach(function (imagepath) {
var img = document.createElement("img");
img.className = "class";
img.src = imagepath;
// div.innerText = text;
img.classList.add("li-added");
container.append(img);
});
document.getElementById("pic1").src= "/" + text;
</script>
I use the same format for split text and it works, but am not sure what am getting wrong in the image part. I will appreciate any assistance or any other way to achieve this. Thanks.
I still don't know exactly what you intend to do. However, I tried to tidy up your code. In the HTML I got rid of the non-unique IDs by replacing them with class attributes.
In your JavaScript code I replaced the lengthy vanilla-JavaScript expressions by suitable jquery expressions and avoided some (temporary) variables altogether. The following is valid HTML and working JavaScript but might not be what you intended:
// var desc = $('#desc').val();
var data=[{image:"MyImage-1591506118979.png"},
{image:"MyImage-1591507932201.jpg"},
{image:"photos-1591548210637.jpg,photos-1591548210640.png"},
{image:"MyImage-1591494888039.png"},
{image:"MyImage-1591505437596.jpg"},
{image:"MyImage-1591084895899.jpg"},
{image:"MyImage-1591085173153.jpg"},
{image:"MyImage-1590905192772.JPG"}];
$("#container").html(data.map(item=>
`<input type="text" class="desc" value="${item.image}" /><br>`
+ item.image.split(',').map(pth=>`<img class="pic1" src ="${pth}" alt="${pth}"><br>`)).join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

How can I save CSS property for the next JavaScript code(execution)?

I want to change the HTML element, which the ID is D-image, and use it as a prediction model. I tried to change CSS but it won't let me save it.
The only thing I want to do is change its CSS filter property and use a changed(means greyed) D-image element to predict.
Here is my BODY HTML code
<div>Teachable Machine Image Model</div>
<button type="button" onclick="init()">Start</button>
<button type="button" onclick="predict()">predict</button>
<script class="jsbin" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="file-upload">
<button class="file-upload-btn" type="button" onclick="$('.file-upload-input').trigger( 'click' )">Add Image</button>
<div class="image-upload-wrap">
<input class="file-upload-input" type='file' onchange="readURL(this);" accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content">
<img class="file-upload-image" id="D-image" src="#" alt="your image" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove
<span class="image-title">Uploaded Image</span>
</button>
</div>
</div>
</div>
<div id="webcam-container"></div>
<div id="label-container"></div>
Here is my original javascript code
<script type="text/javascript">
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image
// the link to your model provided by Teachable Machine export panel
const URL = "https://teachablemachine.withgoogle.com/models/ca88ZGYrw/";
let model, webcam, labelContainer, maxPredictions;
// Load the image model and setup the webcam
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
// run the webcam image through the image model
async function predict() {
// predict can take in an image, video or canvas html element
var image = document.getElementById("D-image")
const prediction = await model.predict(image, false);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
}
</script>
I also tried this but when I do prediction it won't let me use the changed D-image element.
<script type="text/javascript">
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image
// the link to your model provided by Teachable Machine export panel
const URL = "https://teachablemachine.withgoogle.com/models/ca88ZGYrw/";
let model, webcam, labelContainer, maxPredictions;
// Load the image model and setup the webcam
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
// run the webcam image through the image model
async function predict() {
// predict can take in an image, video or canvas html element
var image = document.getElementById("D-image").style.webkitFilter = "grayscale(100%)";
const prediction = await model.predict(image, false);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
}
</script>
Is there any way to save changed CSS property for the next javascript code(execution)?
CSS does not modify the image data so you can't use it to pass a modified image to a JS function. The resulting image data after CSS has been applied is not available to your JS code at all. All you can access is the original image data.
BTW, your code causes the image variable to be equal to the string "grayscale(100%)" because the result of any assignment expression is the value assigned, so document.getElementById("D-image").style.webkitFilter = "grayscale(100%)" returns "grayscale(100%)" , then you are assigning that result to your variable instead of the image element. That is why it breaks when you do that.
You have to modify the image data. There are ways to get the raw image data
Once you have that data, you have to do some processing to make it grayscale, CSS cannot serve as a shortcut here. Maybe this will help.
After you have modified the image data, you have to turn it into a format your function can accept. It looks like it accepts HTML elements so figure out how to change it back into an image element and you should be good.

jquery update the object data value dynamically?

url
http://localhost/news-events/news.html?file=hosted_service.pdf
Js code
parseURL : function() {
var _path = window.location.pathname;
console.log(_path);
var _locationSearch = location.search;
var _locationParse = _locationSearch.replace('?file=','');
console.log(_locationParse);
var filePath = "/pdffiles/"+_locationParse ; // /pdffiles/hosted_service.pdf
$('.divEmbed object').data(filePath); **How to set the data of object? this is wrong**
console.log(filePath);
}
Html
<div class="divEmbed">
<object data="" type="application/pdf">
alt : It appears you don't have a PDF plugin for this browser.
Click here to Download the file.
</object>
</div>
What would the syntax be if i want to add the data of the object = filepath
You're setting jQuery's data object, when in fact what you want is to change an ordinary attribute. Use this instead:
$('.divEmbed object').attr('data', filePath);

Get url query string and use as src on iframe

I'm completely new at javascript and I'm wondering about something really elementary here. I've got an iFrame that I want a dynamic src on. This src(source) should just be a variable. And then a script sets that variable before the frame is loaded.
It's actually a webpart in Sharepoint 2010, so I set up the webpart and edit it's HTML source to something like this:
<script language="JavaScript">
var qs = getQueryStrings();
var myParam = qs["myParam"];
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
} </script>
<iframe height="500" src="(myParam);" width="800"></iframe>
I'm not even sure the syntax is correct. Basically, I want to insert the variable into the src of the iframe.
you have to give some class or ID to your Iframe.
And then you can call a function which will give src to i frame dyanmically.
from client side use this:
$('#ID_of_Iframe').attr('src','NEW SRC hERE');
Example: $('#ID_of_Iframe').attr('src','www.google.com');
Make your links like this:
File1.PDF
or:
<iframe name='myPdfFrameName'></iframe>
File1.PDF
function loadFrame(href) {
window.frames['myPdfFrameName'].location = href;
return false;
}
EDIT: Easiest is probably using target attribute of a link:
<a href='file1.pdf' target='myPdfFrameName'>File1.pdf</a>

Categories

Resources