Referring to another variable in the same object with jQuery - javascript

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

Related

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

get the html element after created

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.

Handling events on dynamically generated JavaScript objects

I have an object I created in JavaScript. Let's say it looks like this:
function MyObject() {
this.secretIdea = "My Secret Idea!";
};
MyObject.prototype.load = function() {
this.MyButton = $(document.createElement("a"));
this.MyButton.addClass("CoolButtonClass");
this.MyButton.click = MyButton.onButtonClick;
someRandomHtmlObject.append(this.MyButton);
};
MyObject.prototype.onButtonClick = function(e) {
alert(this.secretIdea);
};
As you can see, I have an object setup in JavaScript and, when it's loaded, it creates an anchor tag. This anchor tag as a background image in CSS (so it's not empty).
Now, I understand that the 'this' statement, when the button would actually be clicked, would fall to the scope of the MyButton element rather than the object I have created.
I have tried using call(), try() and bind() and I cannot get this to work. I need it so that, when the button is clicked, it goes back to the object's scope and not the html element's scope.
What am I missing here?
The this value inside the click event handler refers to the DOM element, not to the object instance of your constructor.
You need to persist that value, also you refer to MyButton.onButtonClick I think you want to refer the onButtonClick method declared on MyObject.prototype:
MyObject.prototype.load = function() {
var instance = this;
//..
this.MyButton.click(function (e) { // <-- looks like you are using jQuery
// here `this` refers to `MyButton`
instance.onButtonClick(e);
});
//...
};

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.

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

Categories