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

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>");
});

Related

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
});
});

Add Text To Span After Image Error

Note: I am very new to Javascript.
Here is my attempt at achieving this:
$("#img").onerror = function(evt) {
$(".card-error").next("#img-error").html("Error with image url");
});
This did not work.
When an "onerror" occurs - how do I add a text error message inside my "img-error" span?
Try that instead:
$('#img').error(function () {
$(".card-error").html("Error with image url");
});
You need to use an jQuery event handler method:
$('#img').on("error", function() {
$("#img-error").text("Error with image url");
});
You were assigning a property "onerror" to the jQuery wrapper object, where it does nothing than getting garbage-collected. Assigning to the DOM element would've worked, such as
$("#img").get(0).onerror = … // or with plain DOM:
document.getElementById("img").onerror = …

event when adding element into document

Adding new html string into the page:
document.getElementById('container').innerHTML = '<div id="child"></div>';
Is there an event that let me know when child element is in the document?
I have a function, which return some html codeas a string. And when this html will be added in the document, I need to execute javascript function. I've tried to use inline onload event
document.getElementById('container').innerHTML = '<div id="child" onload="console.log(\'ready!\');"></div>';
but it does not seem to work.
UPDATE:
Probably, I should provide more details about the situation. I have a library function
myLibrary.getHtml()
In old version, users just call this function and append the result into the document:
document.getElementById('container').innerHTML = myLibrary.getHtml();
In new version, the result is not a plain html. Now users can interact with it after they append it in the document. So after they append html into the document, I need to go through the result DOM and attach event handlers, hide some elements and other things. That is why, I need to know when they add it in the document and execute a javascript function, which turn plain html into fancy interactive widget.
You could try using DOM Mutation Events, but they are still inconsistently implemented across browsers.
If i have not misunderstood the question, you can probably get this to work
document.getElementById('id').childNodes;
If you can use jQuery, you could write your own custom event which would call the function you need to call whenever the new html has been added:
$('#container').bind('changeHtml', function(e) {
// Execute the function you need
});
And of course instead of just adding the html to the element, you would need to wrap it up in a function which triggers your custom event. Then all you'd need to do is call this function instead of setting the innerHtml yourself.
function addHtml(html) {
$('#container').innerHTML = html;
$('#container').trigger('changeHtml');
}
Solved by myself this way:
myLibrary.getHtml = function() {
var html;
...
var funcName = 'initWidget' + ((Math.random() * 100000) | 0);
var self = this;
window[funcName] = function() { self._initWidget(); };
return html + '<img src="fake-proto://img" onerror="' + funcName + '()"';
}
The idea behind the code is that I specify incorrect url for the src attribute of the img tag and the image triggers error event and call my function. Quite simple :)

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

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");

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