HTMLImageElement node instead of real image - javascript

I'm dynamically creating some image elements, everything is good but when i am trying to wrap this images in li elements i have strange response in DOM, which is: [object HTMLImageElement].
This is the code, please note that element crating function and requireJS are working fine, the problem is by wrapping side.
$.each(images, function(key, value){
requirejs(["globals"], function(){
var _image = createEl("img", {
className: "thumb",
src: photosTempUrl + value
});
var image = $('<li>' + _image + '</li>');
image.appendTo('#js-thumbsBox');
});
});
Thx for help.

You have created an element (_image = createEl(...)) and are then converting it to a string (which, just like any object, results in [object ConstructorName])
Instead, try:
var image = $("<li>");
image.append(_image);
image.appendTo("#js-thumbsBox");

Related

jscript to run at window.onload AND item.onchange

I'm using jscript to load a string in to several elements of an array, then display the useful element in html.
There's a pulldown menu that causes the string to change. So, I need the function to be re-run when that happens.
I have been able to successfully display the element using window.onload
and, I have been able to successfully display the element AFTER the pulldown menu has been changed.
But, I can't seem to display the element with window.onload and subsequently after item.onchage
If anyone has any suggestions, I'd be grateful.
Here is the code that works for window.onload
window.onload = function() {
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
//loads the string in to an array and returns the 2nd element
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
}
Here is the code that works for pulldown.onchange
jQuery(function(){
jQuery('.dropdownimage-format select').on('change', function(){
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
});
In both cases, the element is displayed in html by
<a id="MASNUM">

Populate an input field with an image src in javascript

I have an XHR response that returns images. I have my function in order to show the images. I am combining JQuery and JS in the same code snippet. So far all is working well:
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var lien = leselements[i].url;
//place image urls in img src
output += "<img src='" + lien + "' class='imgs'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;}
But I would like to allow users to click an image and then populate an input field ('#imageurl') with the clicked image src. Here is what I tried but it does not work.
$('.imgs img').click(function(){
$('#imageurl').val() = "";
var source = $(this).attr('src');
$('#imageurl').val() = source;
});
Any help will be greatly appreciated. TIA.
Using .val() in this way will just return the current value of #imageurl.
$('#imageurl').val()
.val is a function call that works as a getter and a setter.
To set the value, try this:
$('#imageurl').val(source);
$('#imageurl').val("");
// ...
$('#imageurl').val(source);
See the documentation.
Try this:
$('img.imgs').click(function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
If the image will be rendered after the attachment of the event handler use this:
$('img.imgs').live('click', function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
Thank you guys for your prompt answers. I tried all of them but they did not work for me. I then asked a friend and we finally found a way to make it work. Probably not the best or professional way but it works. Here is the solution if ever anyone needs it.
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var link = leselements[i].url;
//Place urls in image src and pass in 'link' parameter to the getsrc function
output += "<img src='" + link + "' onclick='getsrc(\""+link+"\")'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;
}
function getsrc (link) {
//console.log($(this));
$('#imageurl').val("");
// var source = $(this).attr('src');
//place imageurl value by passing in the link parameter.
$('#imageurl').val(link);
}

Firefox wont reset jquery created element

This probably is a duplicate but I don't know how to express what is happening in a title description.
I have an image element which i delete and re-create with the click of a button, basically i apply filters with php to an image, and delete the previous element to replace it with the new image to display the new filter.
the code to create the element:
function pictureReset(data) {
$( ".filteredImg" ).remove();
var elem = document.createElement("img");
elem.setAttribute("class", "filteredImg");
elem.setAttribute("height", "328");
elem.setAttribute("alt", "");
elem.src = 'contest/filtered_'+tempFilePath;
document.getElementById("filteredImgContainer").appendChild(elem);
}
the code to apply the filter: (i have several filters but the code is the same, they just call a different php file
$('#sepia').click(function () {
var filePathName = tempFilePath;
$.ajax({
type: 'POST',
url: 'php/sepia.php',
dataType : 'text',
data: {
FilePath : filePathName
},
success: function (data) {
pictureReset();
}
}).done(function(response){console.log(response);});
});
now the problem is although it works fine on chrome, i.e. when i click the button the old image is removed and replaced with the new filtered image, on firefox although it refreshes, somehow it retrieves the old image (even though it doesn't exist because on the server if i retrieve the image the filter is applied), and displays the old filter instead of the new one. Any ideas as to why this is happening??
Apart from adding the parameters, you can also improve the code. Since you are already using jQuery.
You can replace this code:
function pictureReset(data) {
$( ".filteredImg" ).remove();
var elem = document.createElement("img");
elem.setAttribute("class", "filteredImg");
elem.setAttribute("height", "328");
elem.setAttribute("alt", "");
elem.src = 'contest/filtered_'+tempFilePath;
document.getElementById("filteredImgContainer").appendChild(elem);
}
With:
function pictureReset(data) {
var elem = $('<img class="filteredImg" alt="" style="height:328px;" src="contest/filtered_' + tempFilePath + '?t="' + $.now() + ' />');
$("#filteredImgContainer img.filteredImg").replaceWith(elem);
}
I used jQuery replaceWith for this code.

jQuery each returning only last element, Google charts API

I've the following code which will take an array and append to the page dynamically a QR code with the text being an element in the array.
$(document).ready(function () {
var list = ['dog', 'cat', 'mouse', 'hippo', 'ox'];
var qrUrl = 'https://chart.googleapis.com/chart?';
//functions
function getQrCodes(array) {
$.each(array, function (ix, val) {
//options gets chl property redefined for each element
//in the array
var options = {
cht: 'qr',
chs: '300x300',
chl: array[ix]
}
qrOptionArray.push(options);
console.log('this qr should be: ' + array[ix]);
console.log(qrUrl + $.param(options));
var $img = $('img').attr('src', qrUrl + $.param(options)).appendTo('body');
});
}
getQrCodes(list);
});
You can see the console output from the fiddle here although for some reason the QR codes don't appear in the fiddle window, they do on my local machine. The problem I've got is that the last regardless of the fact that you can see the console output change for each element in the array, the only QR code I get is the last element in the array repeated X number of times. Each of those QR cans will scan and print 'ox', even though the console output is correct. What's going on here?
The selector where you append the image to the body is wrong. You are selecting all existing img elements, whereas you want to create a new one. Try this:
var $img = $('<img />').attr('src', qrUrl + $.param(options)).appendTo('body');
Example fiddle
Note: $('<img />') not $('img').

Setting a background image with external js file

Im having an issue with setting my bacground image by using an external js code.
this is the code of the js:
$(document).ready()
{
mazdaArr = new Array();
for (i=1;i<6;i++)
{
mazdaArr[i-1]= new Image();
mazdaArr[i-1].src = 'mazda/mazda'+[i]+'.jpg';
}
$('mainContent').css('background-image','url(/mazda/mazda4.jpg)');
$('mainContent').css('background-image', 'url(' + mazdaArr[3].src + ')');
console.log(mazdaArr[3].src);
}
everything works fine but the css attr, since I can see at the console the right link and when I click it, the image will open up in new tag. by that i guess the jquery call from html page is fine.
cant find what goes wrong here...
A few things:
Looks like your string is concatinating an array literal, and not the integer i. So 'string'+[]+'string' is effectively 'string' + new Array() + 'string'.
Your selector for mainContent needs to either be looking for a class or an ID so either .mainContent or #mainContent.
Finally, you don't need to instantiate a new Image since jQuery will just update the CSS of the element with a new string for the background-image property.
Try
$(document).ready(function() {
var mazdaArr = [],
i = 0;
for (i; i<5; i++) {
mazdaArr[i] = 'mazda/mazda'+ i +'.jpg';
}
$('#mainContent').css('background-image', 'url(' + mazdaArr[3] + ')');
console.log(mazdaArr[3].src);
});

Categories

Resources