get the html element after created - javascript

i'm creating a img when i click in a input, then i get the html or anyelse from the created img.
but i dont know why this is not working!
always return null
my js:
$("#click").click(function(){
var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
$(this).after($imgDone);
setTimeout(function(){
alert($(this).next().html());
}, 1000);
});
i mande a exp.: Demo

this is pointing at the wrong place in setInterval.
The this you have in the outer scope isn't the same as the this that you get inside the callback, which will usually be the window object, since:
setInterval(f, t)
is actually
window.setInterval(f, t);
To solve the problem, take a copy of this in the outer scope:
$("#click").click(function(){
var self = this;
var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
$(this).after($imgDone);
setTimeout(function(){
alert($(self).next().html());
}, 1000);
});
For efficiency, as #T.J. Crowder suggests, you could actually use the jQuery constructor to take that copy, and save yourself a few calls to jQuery:
$("#click").click(function(){
var $this = $(this);
var $imgDone = $('<img/>')
.attr({src: 'someImage/insomewhere.jpg'})
.insertAfter(this); // NB: not $this here
setTimeout(function(){
alert($this.next().html());
}, 1000);
});
The other problem is that .html() shows the inner contents of tags, not the tags themselves, and your img tag has no inner contents.
There doesn't appear to be any builtin jQuery method that returns the actual whole HTML of an element. To do that you'd need to put your element into something else (e.g. a <div>) and then take the .html() of that.
Here's a plugin I just made that does this, inspired by something I found via Google:
(function($) {
$.fn.outerhtml = function() {
return $('<div/>').append(this.clone()).html();
};
})(jQuery);
Demo of it in use on your problem at http://jsfiddle.net/alnitak/qaSmS/

because the timeout function is called form a different context, this no longer applies.
$("#click").click(function(){
var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
$(this).after($imgDone);
myImg = $(this);
setTimeout(function(){
alert($(myImg).next().html());
}, 1000);
});

The ".html()" method gets the contents of something, not including the markup for the container itself.
The other answers indicating that the use of this in the timeout handler are correct, of course. When you fix that, however, the alert will just be empty.

Related

Assigning a jquery object to a variable doesn't work as expected

Can someone explain why one of these versions of code works and the other fails?
This doesn't work:
var classForSelectedElement = "hightlight";
var prevSelect = $(".form-element");
var $selectedElement = $("div").on("click", ".form-element",function(e){
prevSelect.removeClass(classForSelectedElement);
$(this).addClass(classForSelectedElement);
});
Whereas this works:
var classForSelectedElement = "hightlight";
var $selectedElement = $("div").on("click", ".form-element",function(e){
$(".form-element").removeClass(classForSelectedElement);
$(this).addClass(classForSelectedElement);
});
Why?
Presuming that the .form-element elements are appended to the DOM dynamically after load (due to your usage of a delegated event handler) then the first example doesn't work as you are attempting to retrieve the .form-element on load of the page before they exist.

second this is wrong? [duplicate]

I'm not quite sure if I'm not using this in the correct scope or what, but I have a script that basically captures a link click and causes the page to fade out before going to the linked page. However, if the link is a JavaScript onclick, the script fails.
Here's my code:
<script type="text/javascript">
pageObj = {
init: function(){
$("body").fadeTo("slow", 1);
},
redirectPage: function(redirect){
window.location = redirect;
},
linkLoad: function(location){
$("body").fadeOut(1000, this.redirectPage(location));
}
};
$(document).ready(function() {
pageObj.init();
$("a").click(function(e){
e.preventDefault();
if (this.attr('onclick') !== undefined) {
eval(this.attr('onclick').val());
} else {
var location = this.href;
pageObj.linkLoad(location);
}
});
});
</script>
As you can see, I'm trying to do a check to see if the link has the onclick attribute, and then call the onclick function if it exists. How can I achieve this?
Use: $(this).attr instead of this.attr
This forces it into the context of jQuery.
While Diodeus is correct that you need to wrap this in a jQuery collection before using attr() (it's a method of a jQuery collection, not of an HTMLElement), you can just as well skip attr().
$("a").click(function(e){
var location;
e.preventDefault();
if ($.isFunction(this.onclick)) {
this.onclick.call(this, e);
} else {
location = this.href;
pageObj.linkLoad(location);
}
});
Note that I used the property (when an HTML document loads, attributes are usually preloaded into properties, with on_______ attributes being preloaded as methods. Also note that I used this.onclick.call() rather than eval(), setting the correct this for onclick methods, and ensuring access to the event object as an argument.

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

How to refer to object in JavaScript event handler?

Note: This question uses jQuery but the question has nothing to do with jQuery!
Okay so I have this object:
var box = new BigBox();
This object has a method named Serialize():
box.AddToPage();
Here is the method AddToPage():
function AddToPage()
{
$('#some_item').html("<div id='box' onclick='this.OnClick()'></div>");
}
The problem above is the this.OnClick() (which obviously does not work). I need the onclick handler to invoke a member of the BigBox class. How can I do this?
How can an object refer to itself in an event handler?
You should attach the handler using jQuery:
function AddToPage()
{
var self = this;
$('#some_item').empty().append(
$("<div id='box'></div>")
.click(function() { self.OnClick(someParameter); })
);
}
In order to force the event handler to be called on the context of your object (and to pass parameters), you need to add an anonymous function that calls the handler correctly. Otherwise, the this keyword in the handler will refer to the DOM element.
Don't add event handlers with inline code.
function AddToPage()
{
$('#some_item').html("<div id='box'></div>");
$('#box').click(this.OnClick);
}
EDIT:
Another way (avoids the extra select):
function AddToPage()
{
var div = $('<div id="box"></div>'); // probably don't need ID anymore..
div.click(this.OnClick);
$('#some_item').append(div);
}
EDIT (in response to "how to pass parameters");
I'm not sure what params you want to pass, but..
function AddToPage()
{
var self = this, div = $('<div></div>');
div.click(function (eventObj) {
self.OnClick(eventObj, your, params, here);
});
$('#some_item').append(div);
}
In jQuery 1.4 you could use a proxy.
BigBox.prototype.AddToPage= function () {
var div= $('<div>', {id: box});
div.click(jQuery.proxy(this, 'OnClick');
div.appendTo('#some_item');
}
You can also use a manual closure:
var that= this;
div.click(function(event) { that.OnClick(event); });
Or, most simply of all, but requiring some help to implement in browsers that don't yet support it (it's an ECMAScript Fifth Edition feature):
div.click(this.OnClick.bind(this));
If you are using jQuery, then you can separate your code from your markup (the old seperation of concerns thing) like this
$(document).ready(function() {
var box = new BigBox();
$('#box').click(function() {
box.serialize();
});
});
You only need to add the click handler once for all divs with id of box. And because the click is an anonymous function, it gets the scope of the function it is placed in and therefore access to the box instance.

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