i'm implementing this tenor API into my Site....the thing is that with this function I retrieve a single value single gif...How do I foreach() all of them?
How would need to be the html structure and the javascript loop
JAVASCRIPT/ JSON
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "*************";
var lmt = 8;
.....
// callback for trending top 10 GIFs
function tenorCallback_trending(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
document.getElementById("preview_gif").src = top_10_gifs[1]["media"][0]["nanogif"]["url"];
document.getElementById("share_gif").src = top_10_gifs[6]["media"][0]["tinygif"]["url"];
return;
}
I would have this top_10_gifs variable loaded of content...how do I foreach it?
HTML
<h2 class="title">GIF loaded - preview image</h2>
<div class="container">
<img id="preview_gif" src="" alt="" style="">
</div>
<h2 class="title">GIF loaded - share image</h2>
<div class="container">
<img id="share_gif" src="" alt="" style="">
</div>
Depends on what exactly you're trying to do (which you haven't explained), but something like
response_objects.results.forEach((gifObj, i) => {
if (i >= 8) return;
// do something with each gifObj
document.querySelector('.container')
.appendChild(document.createElement('img'))
.src = gifObj.media[0].tinygif.url;
});
to iterate over all of them.
Related
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.
I am trying to display each image from each post from medium's rss feed, without using JQuery, but only javascript or angular, in HTML.
Is it possible to get the image from the RSS feed? I am receiving the title, the date it was created at and the link.
I am working with Ionic2.
entries: any = null;
image: any = null;
In my constructor:
Feed.load('https://medium.com/feed/#jaymelone', (err, rss) => {
if (err) {
console.log(err);
}
else {
this.entries = rss.items;
this.image = this.entries.find('img').eq(0).attr('src');
}
console.log("RSS function - entries:", this.entries);
console.log("RSS function - image: ", this.image);
});
In my HTML
<div class="post" *ngFor="let entry of entries">
<div class="inner">
<img class="img" [src]="entry.image">
<p class="title">{{entry.title}}</p>
</div>
</div>
But I receive:
<img class="img" src="undefined">
And:
TypeError: Array.prototype.find callback must be a function
Assuming that your console.log call is outputting the image name correctly, everything looks in order except you need to use ng-src instead of src, like this:
<img class="img" ng-src="{{entry.image}}">
Try entry.image.url.
Example:
<img class="img" [src]="entry.image.url">
I recently learned about Sub Resource Integrity which prevents the execution of altered JS and CSS. Since the current implementation lacks the support for images I tried to experiment with my own implementation.
<img data-src="http://localhost:8888/4.jpg" alt="" data-hash="" class="image">
<img data-src="http://localhost:8888/2.jpg" alt="" data-hash="" class="image">
<img data-src="http://localhost:8888/3.jpg" alt="" data-hash="" class="image">
<script src="qwest.js"></script>
<script src="md5.min.js"></script>
<script>
var images = document.getElementsByClassName("image");
for( var i = 0, len = images.length; i < len; i++){
popHash(images[i]);
}
function popHash(image) {
qwest.get(image.dataset.src, {}, {responseType:"blob"})
.then(function (xhr, response) {
var src = window.URL.createObjectURL(response);
image.src = src;
image.dataset.hash = md5(src);
console.log(image.dataset.hash);
/* code to check the equality of hashes here */
})
}
</script>
The problem is each time I am getting a different MD5 hash. Please help me to find what I am doing wrong.
I am using JavaScript-MD5 (https://github.com/blueimp/JavaScript-MD5) for getting MD5 hash and Qwest.js (https://github.com/pyrsmk/qwest) for fetching the Image
With Slight Changes I was able to get the correct result. I used arrayBuffer instead of blob and a sha-256 hashing. I made a tiny library for the same.
https://github.com/ShopupStore/IntegrityChecker
I'm just a beginner in javascript, I'm trying to make javascript take image src from specific image with a specific class and place the src into div.
<div class="result"></div>
<div class="ilist">
<img src="images/dog.jpg" class="thumbnail">
<img src="images/bird.jpg" class="thumbnail">
<img src="images/cat.jpg" class="selected__img"> // THIS IS THE DESIRED IMAGE
</div>
What i want to show in the result div is this = images/cat.jpg
but instead it doesn't display anything or some weird stuff...
javascript right now
var simg = document.getElementsByClassName('selected__img').src;
document.getElementsByClassName("result").innerHTML = simg;
Sorry for being such a newbie but I'm trying to learn..
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Try this:
<script>
var simg = document.getElementsByClassName('selected__img');
var src=simg[0].src;
var resutlObj=document.getElementsByClassName("result")[0]
resutlObj.innerHTML = src;
</script>
Full code snippet:
var simg = document.getElementsByClassName('selected__img');
var src = simg[0].src;
var resutlObj = document.getElementsByClassName("result")[0]
resutlObj.innerHTML = src;
<div class="result"></div>
<div class="ilist">
<img src="https://loremflickr.com/100/100?random=1" class="thumbnail">
<img src="https://loremflickr.com/100/100?random=2" class="thumbnail">
<img src="https://loremflickr.com/200/200?random=3" class="selected__img"> // THIS IS THE DESIRED IMAGE
</div>
getElementsByClassName is a NodeList collection. So you need to take individual nodes with [0]:
var simg = document.getElementsByClassName('selected__img')[0].src;
document.getElementsByClassName("result")[0].innerHTML = simg;
In this specifc case it's more convenient to use querySelector metod which returns one element:
var simg = document.querySelector('.selected__img').src;
document.querySelector(".result").innerHTML = simg;
or since you are using jQuery:
var simg = $('.selected__img').attr('src');
$(".result").text(simg);
$(document).ready(function() {
$('img').hover(function(){
$('.result').html($(this).attr('src'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result">Image path</div>
<div class="ilist">
<img src="images/dog.jpg" class="thumbnail">
<img src="images/bird.jpg" class="thumbnail">
<img src="images/cat.jpg" class="selected__img"> // THIS IS THE DESIRED IMAGE
</div>
You need to iterate over elements, since you have one selected__img you can use 0 like below:
var simg = document.getElementsByClassName('selected__img')[0].src;
document.getElementsByClassName("result").innerHTML = simg;
I am trying to do something that is slightly more complicated than I am used to, and I was hoping you guys could help me with this one... The website I am developing requires this type of Psudo
<script>
function FirstPic(){
document.titlepic.src = document.rep1.src
return
}
function SecPic(){
document.submitpic.src = document.rep2.src
return
}
</script>
// Calling Image Replacements
<img style="visibility:hidden;width:0px;height:0px;" name="rep1" src="title2.gif>
<img style="visibility:hidden;width:0px;height:0px;" name="rep2" src="submit2.gif>
// End of Calling Image Replacements
// Output Area
<img src="title.gif" name="titlepic">
<input type="radio" onclick="FirstPic();SecPic();updateProductPrice(this);parent.specs.location='<?php echo $options_item['base_var'] ?>.htm';">
<img src="submit.gif" name="submitpic">
// End of Output Area
You can replace the sources of as many images as you would like with a single click. And a single function, you don't need a function per each image.
demo
HTML:
<img src='source-img-1.jpg' class='s'>
<!-- as many source images as you would like -->
<button id='replace'>Replace</button>
<img src='destination-img-1.jpg' class='d'>
<!-- as many destination images as you have source images -->
JavaScript:
var r = document.getElementById('replace');
r.addEventListener('click', function(){
var s = document.querySelectorAll('.s'),
d = document.querySelectorAll('.d'),
l = s.length;
if(d.length != l) return;
for(var i = 0; i < l; i++) d[i].src = s[i].src;
}, false);
Also, use a CSS stylesheet, don't use inline styles.