Using jquery append() in <head> (in a function/class) - javascript

I want to use the append() function from inside the <head>, in a function to be specific, like so:
function custom_img(src_img)
{
$("div").append("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");
This is a quick example that I just wrote out. I want my function to make a new image like that every time I create a new object like this. Obviously this doesn't work, since the append() requires to be in the body (I've tried this).
How would I do this?

The reason it's not working is because your div does not exist yet.
So you can either use the $(document).ready() function to wait for the document to load.
Or if you want the images to load together with the rest of the document, you could simply create a new div and insert the images there.
var div = $("div")
function custom_img(src) {
div.append($("img").attr("src", src));
}
Then when the document is fully loaded, you can go through the array and insert the loaded images in the DOM.
$(document).ready(function() {
$("#myDiv").append(div);
});

You can try using .after(), or even .html()
function custom_img(src_img)
{
$("div").after("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");
or
function custom_img(src_img)
{
$("div").html("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");

Related

Avoid wrong interpretation of source with document.createElement for dynamic sources

I have script that I would like visitors on my website to run when they load a web page. It looks like this:
window.onload = function(){
var pxl=document.createElement('img');
pxl.setAttribute('src', 'http://localhost:8080/getTrackingPixel')
document.body.appendChild(pxl);
}
Most of the times the source returns an image and it works fine. However, sometimes it returns this:
<html><body style="background-color:transparent"></body></html>
And I can't really change the fact that it might sometimes not return an image. How do I change the javascript so that it can handle the html response without any errors? It might be possible for me to predict when it happens though - but I haven't managed to find a good way to request the source and return the html either.
You can achieve it by using the javascript Image object which, unlike the createElement approach, allows you to fetch the src url before inserting the img in the DOM.
The onload event of the Image object won't fire if the loaded content isn't an img.
Here it is :
window.onload = function(){
var pxl = new Image();
pxl.onload = function(){
// is IMG
document.body.appendChild(pxl);
}
pxl.onerror = function(){
// is not IMG
// Meaning in your case : <html><body style="background-color:transparent"></body></html>
}
pxl.src = 'http://localhost:8080/getTrackingPixel';
}
(Note that your code also missed the semicolon ";" line 4)

How to target the replaced content after using `replaceWith`?

I want to use Jquery (1.10.2) to replace some content on my site with the results of a API request. Then I want to execute some more javascript on that content. I know the new content is HTML, but I don't anything about it. Even if it has an #id, or ".class" assocated with it, thus I cannot target the content.
jQuery.replaceWith() will return the OLD "this"; How do I get the "this" for the new content?
http://jsfiddle.net/G24X8/3/
$('#fix').on('click', function() {
$('#myStuff').replaceWith("<p>Hello new world!</p>"); // Hello new world content actually comes from a server
// since replaceWith returns the old content, how do I get the $(?this?) for the new content, when I don't know what is in it?
});
-daniel
You can just do this way to get hold of the newContent after adding it to DOM, if that is what you meant:
$('#fix').on('click', function() {
var $newCont = $("<p>Hello new world!</p>");
$('#myStuff').replaceWith($newCont);
//Do anything with $newCont
//$newCont.css('color', 'blue');
});
I suggest using .html() instead of .replaceWith() -- that way you're only replacing the contents of the target tag, not the tag itself.
$('#fix').on('click', function() {
$('#myStuff').html("<p>Hello new world!</p>");
//...
$('#myStuff').doSomethingElse(); //whatever else you need to do
});
Try this:
$('#fix').on('click', function() {
$('#myStuff').text('').html("<p>Hello new world!</p>");
});

Referring to another variable in the same object with jQuery

Alright, so I'm completely new to jQuery, so here goes:
I have a GameCard object which accepts a div in it's "constructor" which is then assigned to a variable. Within the object, I want to perform a function when that div is clicked.
function GameCard(imageSource, div)
{
this.cardImage = new Image();
this.cardImage.src = imageSource;
this.hiddenImage = new Image();
this.hiddenImage.src = HIDDEN_SOURCE;
this.div = div;
$(this).WHAT_HERE_?.click(function()
{
});
}
pretty much how do you refer to another variable within the same object using javascript?
Thanks in advance!
You wrap the div using the jQuery function.
$(div).on('click',function(){
//do stuff
});
What is the id of your div?
Don't use $(this) in this context.
$("#IdOfDiv").click(function(){});
But wrap the above in this;
$(function(){});
This ensures that the jQuery code is not run until the document is loaded.
So;
$(function(){ $("#IdOfDiv").click(function(){
//Do someting
});
});

Browser is not smooth while using jQuery "replaceWith"

I'm using jQuery replaceWith to update information of my website. Div elements which are returned are small. The function is called after 5 minutes. When I focus on browser, replaceWith function will run but my browser is not smooth and sometime can crash. Which plugin or solution can I use to resolve the problem ?
I used:
$('#hotpost').hide().html(newHtml).fadeIn("slow");
$('#hotpost div.content').hide().replaceWith(newHtml).fadeIn("slow");
I believe you should compile your HTML into a document fragment
using for example, this function
var compileHTML = function (html) {
var div = document.createElement("div");
div.innerHTML = html;
var fragment = document.createDocumentFragment();
while ( div.firstChild ) {
fragment.appendChild( div.firstChild );
}
return fragment
};
before appending your HTML into your new div
like so:
$('#hotpost').hide().html(compileHTML(newHtml)).fadeIn("slow");
Plus I saw that in your code you're usin setInterval which when blurring the window can have unexpected behaviours, you could use this:
(function loop(){
//what you need to do
$('#hotpost').hide().html(compileHTML(newHtml)).fadeIn("slow"); //for example
setTimeout(loop, (18000));
})();
this new loop will wait until the code inside is executed before looping again, rather than executing the code and ("no", says browser, "user is using memory in an other tab")
And when you go back to your page, multiple animations happen at the same time...

Wait for iframe to load in JavaScript

I am opening an iframe in JavaScript:
righttop.location = "timesheet_notes.php";
and then want to pass information to it:
righttop.document.notesform.ID_client.value = Client;
Obviously though, that line isn't going to work until the page has fully loaded in the iframe, and that form element is there to be written to.
So, what is the best/most efficient way to address this? Some sort of timeout loop? Ideally I would really like to keep it all contained within this particular script, rather than having to add any extra stuff to the page that is being opened.
First of all, I believe you are supposed to affect the src property of iframes, not location. Second of all, hook the iframe's load event to perform your changes:
var myIframe = document.getElementById('righttop');
myIframe.addEventListener("load", function() {
this.contentWindow.document.notesform.ID_client.value = Client;
});
myIframe.src = 'timesheet_notes.php';
Again, this is all presuming you mean iframe, not framesets.
I guess you can pretty easily do this with jQuery... jQuery Home
Just hook the page to the jQuery $ function ()... e.g.
$(document).ready(function() {
$('iframe').load(function() {
// write your code here....
});
});
Have a quick look at the file uploader example here:
Using iframes for multiple file uploads...
iFrame could have dynamically loaded elements and the best option to work with them is to use recursion:
$('iframe').ready(function() {
var triggerMeAgainIfNeeded = function() {
setTimeout(function() {
var neededElm = $('.someElementThatLoadedAfterIframe');
if (neededElm.length > 0) {
// do your job
} else {
triggerMeAgainIfNeeded();
}
}, 10);
}
});
try this one...
$('iframe').each(function() {
$(this).ready(function() {
$('#result').html("ready");
});
});

Categories