I need to get the id of element calling the function,
I have a div like this,
<div id="MainDiv"></div>
Below is the jQuery code,
when i keep a breakpoint and type this I get the things info about the div, but I am not sure of how to get its id, i.e this.id
$(document).ready(function () {
$("#MainDiv").Scrollit();
});
$.fn.Scrollit = function (e) {
alert(this.id);
};
Inside the plugin this refers to the jQuery object, not a dom element so it does not have the id property.
You can iterate through the jQuery object using .each() and get the each element's properties - because the plugin can be initialized on a set containing more than one element
$.fn.Scrollit = function (e) {
this.each(function () {
alert(this.id)
})
};
Demo: Fiddle
Few pointers though
If you are developing a plugin don't depend on the id of the elements, use options or data attributes to pass informations
Also return the jQuery object back to enable chaining
$.fn.Scrollit = function (e) {
return this.each(function () {
alert(this.id)
})
};
Related
I have the following function that I would like to work with a class "pause" instead of an id.
I did see a few topics about this however I didn't quite understand how would this work.
Thanks!!!
function onPlayerReady(event) {
document.getElementById('pause').onclick = function() {
youtubePlayer1.pauseVideo();
youtubePlayer2.pauseVideo();
youtubePlayer3.pauseVideo();
e.preventDefault();
};
};
Using jQuery you can attach a click handler to all elements that have the pause class.
$(".pause").on("click", function () {
youtubePlayer1.pauseVideo();
youtubePlayer2.pauseVideo();
youtubePlayer3.pauseVideo();
e.preventDefault();
});
As you can guess from the name, the getElementsByClassName() function can return multiple (or zero) results. This is because element ids must be unique, but many different elements can have the same class.
So all you need to do is iterate over the results and add the click handler as before:
function onPlayerReady(event) {
var elem = document.getElementById('pause')
for(var i in elem) {
elem[i].onclick = function() {
youtubePlayer1.pauseVideo();
youtubePlayer2.pauseVideo();
youtubePlayer3.pauseVideo();
e.preventDefault();
}
}
};
Even though you only expect a single result, this is how you should do it to prevent errors.
I want to invoke a custom method on a DOM element
like this :
<div id="MyObject">
<!-- some elements -->
</div>
<script>
function doSomething() {
// do something with input DOM element
}
$("MyObject").doSomething();
</script>
How can I develop this problem? Is it necessary to use jQuery or not?
You do not need to use jQuery. You can use document.getElementById('MyObject') to get a reference to the DOM node.
To run your doSomething function on it, you would need to add a node parameter to it something like this:
function doSomething(input) {
// do something with input DOM element
}
doSomething(document.getElementById('MyObject'));
To have it chained, you would need to add to the Element interface which all DOM nodes implement (rereading, I meant inherit from). If you go that way, you could do:
Element.prototype.doSomething = function() {
alert(this);
}
document.getElementById('MyObject').doSomething();
JSFiddle: http://jsfiddle.net/6Lyb4b9p/
MDN: getElementById
Without jQuery, you could do something like
if (typeof $ != 'function') {
//create a function $ which will return the element with said id
window.$ = function(id) {
return document.getElementById(id);
}
}
//Add a method to the Elemen prototype so you can call it on any element object
Element.prototype.doSomething = function() {
this.innerHTML = 'hi from inner';
}
$('MyObject').doSomething();
<div id="MyObject">
<!-- some elements -->
</div>
I found the answer by myself.
I can practice in this way :
<script>
(function ($) {
$.fn.doSomething = function () {
// do something like this
$(this).append("Hello Object");
}
} (jQuery));
$("#MyDOMElement").doSomething();
</script>
I have dynamically generated some input tags for a web application.
function FormElement () {
this.formElement = $('<div class="formElement"></div>');
this.formElement.append('<label for=""></label>');
this.formElement.append('<input type="text" />');
FormElement.prototype.addIds = function (id) {
this.formElement.find('label').attr({'for':id});
this.formElement.find('input').attr({'id':id});
return this.formElement;
};
FormElement.prototype.addLabelText = function (value) {
this.formElement.find('label').html(value);
};
FormElement.prototype.addInputValue = function (value) {
this.formElement.find('input').attr({'value':value});
};
FormElement.prototype.addClass = function (className) {
this.formElement.attr({'class':className});
};
FormElement.prototype.append = function (selector) {
$(selector).append(this.formElement);
};
}
The appended elements do not seem to have associated click, select etc.. events. I read you can you .on(). I would like to associate all possible events to all types of elements in a general way. What is the best way to go about this?
Suppose you want to assign a default behavior on click event for all inputs with a specific class, say 'foo':
$(document).on('click','input.foo', function(){
/* your function here */
});
If you don't go this way and try the following:
$('input.foo').click(function(){
/* your function here */
});
then the behavior will be added only to existing elements, not to those added after the script executed.
you have to use On() function on them
Attach an event handler function for one or more events to the selected elements.
$("button").on("click", 'selector',notify);
$("target").on("change",'selector', notify);
For dynamically generated element's you need event delegation -
$(document).on('change','.yourInputClass',function(){
var value = $(this).val();
});
http://api.jquery.com/on/
I have html like so
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
and I am using JQuery to do this
$('span[rel*=comm]').cust();
and the custom function is as such
$.fn.cust = function () {
$(this).click(function(e) {
alert($(this).val());
});
}
The value of this is 12 even when I click on 2nd span which should give me 82
Any help would be appreciated.
You'll need to return a seperate function for each element in the collection, normally done with return this.each ...
$.fn.cust = function () {
return this.each(function() {
$(this).click(function(e){
alert($(this).val());
});
});
}
And value is not a valid attribute for a span element.
This should work better:
$.fn.cust = function () {
$(this).click(function (e) {
alert($(this).attr('val'));
});
}
span does not have value.
http://jsfiddle.net/dREj6/
Also if you want to make your method chainable you should return an jQuery instance:
$.fn.cust = function () {
return $(this).click(function (e) {
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust().css('color', 'red');
http://jsfiddle.net/dREj6/1/
rel are for links (anchor element) - use class
use data attribute instead of custom attributes
http://jsbin.com/ogenev/1/edit
<span class='comm' data-val='12'>click</span>
<span class='comm' data-val='82'>click</span>
$.fn.cust = function(){
$(this).click(function(){
alert(this.dataset.val);
});
};
$('.comm').cust();
It works if you use .attr('val')
$.fn.cust = function () {
$(this).click(function(e){
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust();
http://jsfiddle.net/fW7FT/
.val() is for input since they're the only one accepting the val attribute officialy
The call $('span[rel*=comm]') returns a JQuery wrapper for all spans matching the selector - the two ones you have in your example are picked both.
Now inside the definition of cust, $(this) refers to the wrapped array, which causes your issue. Use
$(this).each( function() {
$(this).click (...
});
Inisde each $(this) will point to each separate span element in the selection, so they will have the click handler individually attached and working as you expect.
You can achieve what you're looking for with this:
HTML:
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
JS:
var cust = function(source) {
alert($(source).attr('val'));
}
$('span[rel*=comm]').click(function(e) {
cust(this);
});
The JSFiddle working: http://jsfiddle.net/ejquB/
I have a selector where I get the first element like that:
$("#MyControl")[0]
Is it possible to get the element with a function other than accessing the elements like a array?
What I want to do with that is to pass this element to a function with .call() to defines the context.
Here is an example:
$(document).ready(function () {
$(document).on("change", "#MyControl", setActivityControlsState);
});
setActivityControlsState: function () {
var selector = "#automaticActivityCreation";
if ($(selector).length > 0) {
if ($.isNumeric(this.value) && this.value > 0)
$(selector).show();
else
$(selector).hide();
}
}
referenceFormOnSuccess: function (data) {
setActivityControlsState.call($("#MyControl")[0]);
}
As you can see in the refreshFormOnSuccess function, I must defines 'this' with $("#MyControl")[0].
I just want to know if is there a better way to do that.
Note that I don't want to access the value of my control with something like $(this).val()
May I suggest a small re-structuring that mitigates that need:
$(document).ready(function () {
$(document).on("change", "#MyControl", setActivityControlsState);
});
setActivityControlsState: function () {
// cache jquery object instead of just the selector
// for better memory management
var automaticActivityCreation = $("#automaticActivityCreation");
if (automaticActivityCreation.length > 0) {
if ($.isNumeric(this.value) && this.value > 0)
automaticActivityCreation.show();
else
automaticActivityCreation.hide();
}
}
referenceFormOnSuccess: function (data) {
// fire the change event which will tap
// the listener you set up in .ready
$("#MyControl").trigger('change');
}
but if you really want to get the object with jquery you do have some options:
// jQuery select #MyControl and get as dom element with array
$("#MyControl")[0]
// jQuery select #MyControl and get as dom element with .get
$("#MyControl").get(0)
but because you are using an element with an ID and you can only use a single ID at a time you really don't need jquery for this
document.getElementById('MyControl')
or
referenceFormOnSuccess: function (data) {
setActivityControlsState.call(document.getElementById('MyControl'));
}