Get element under a selector with jquery - javascript

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

Related

How to check already given class and add another one

recently I wrote one few lines of js in order to check the DOM structure and add "in" class in case user clicked on link. Now I need to use has property but I dont know how its used. Here is code:
$(document).on('click', '.collapse-all > a', function () {
var $collapseList = $(this).closest('#main-content').find('.collapse-list'),
$container = $collapseList.find('.collapse').removeAttr('style'),
$collapsed = $collapseList.find('.mehr-pfeil');
if ($container.filter('.in').length > 0) {
$container.removeClass('in');
} else {
$container.addClass('in');
}
});
$(function () {
$('.collapse-all > a').click();
});
// here is my try to check the DOM and add another class on <a> element
$(function () {
$container.hasClass('in') {
if ($container.filter('.in').length > 0) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
}
});
So right now everything worked but when I tried to check if js has gave in class to .collapse then my code breaks. Can anyone tell me where I've made mistake
hasClass() returns a bool so your function may check something like this
if($container.hasClass('in')) {
...
}
As noted by TheBlueAussie, your $container is also not in the scope of your ready function.
A quick fix would be to global the variable like so
var $container;
$(document).on('click', '.collapse-all > a', function () {
var $collapseList = $(this).closest('#main-content').find('.collapse-list'),
$collapsed = $collapseList.find('.mehr-pfeil');
$container = $collapseList.find('.collapse').removeAttr('style');
...
}
There are 2 problems in your code
1,$container is not in the scope of your class checking function.
2, The way you used hasClass method is wrong
It will return true or false. So you can check it inside an if condition.
var $collapseList = $(this).closest('#main-content').find('.collapse-list');
$container = $collapseList.find('.collapse');
if ($container.hasClass('in')) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
take a look at
.hasClass() to check if element has a class.
you can use it in a if and than addClass
if($('.class').hasClass('className'))
{
$('.class').addClass('xy');
//or
$('.class').removeClass('className');
//and so on
//.class could be #id as well
}
You should move the hasClass statement to a condition start since this method returns a boolean (true/false) value:
// here is my try to check the DOM and add another class on <a> element
$(function () {
if ($container.hasClass('in')) {
if ($container.filter('.in').length > 0) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
}
});
You should also declare the $container variable inside this function or move its initialization to be a global one.
try this
$container.hasClass('in');
or if you want to toggle class
$container.toggleClass('in')

not able to get ID of calling element in jquery

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

Defining a single jQuery function for separate DOM elements

I have several jQuery click functions- each is attached to a different DOM element, and does slightly different things...
One, for example, opens and closes a dictionary, and changes the text...
$(".dictionaryFlip").click(function(){
var link = $(this);
$(".dictionaryHolder").slideToggle('fast', function() {
if ($(this).is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
});
HTML
<div class="dictionaryHolder">
<div id="dictionaryHeading">
<span class="dictionaryTitle">中 文 词 典</span>
<span class="dictionaryHeadings">Dialog</span>
<span class="dictionaryHeadings">Word Bank</span>
</div>
</div>
<p class="dictionaryFlip">toggle dictionary: off</p>
I have a separate click function for each thing I'd like to do...
Is there a way to define one click function and assign it to different DOM elements? Then maybe use if else logic to change up what's done inside the function?
Thanks!
Clarification:
I have a click function to 1) Turn on and off the dictionary, 2) Turn on and off the menu, 3) Turn on and off the minimap... etc... Just wanted to cut down on code by combining all of these into a single click function
You can of course define a single function and use it on multiple HTML elements. It's a common pattern and should be utilized if at all possible!
var onclick = function(event) {
var $elem = $(this);
alert("Clicked!");
};
$("a").click(onclick);
$(".b").click(onclick);
$("#c").click(onclick);
// jQuery can select multiple elements in one selector
$("a, .b, #c").click(onclick);
You can also store contextual information on the element using the data- custom attribute. jQuery has a nice .data function (it's simply a prefixed proxy for .attr) that allows you to easily set and retrieve keys and values on an element. Say we have a list of people, for example:
<section>
<div class="user" data-id="124124">
<h1>John Smith</h1>
<h3>Cupertino, San Franciso</h3>
</div>
</section>
Now we register a click handler on the .user class and get the id on the user:
var onclick = function(event) {
var $this = $(this), //Always good to cache your jQuery elements (if you use them more than once)
id = $this.data("id");
alert("User ID: " + id);
};
$(".user").click(onclick);
Here's a simple pattern
function a(elem){
var link = $(elem);
$(".dictionaryHolder").slideToggle('fast', function() {
if (link.is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
}
$(".dictionaryFlip").click(function(){a(this);});
$(".anotherElement").click(function(){a(this);});
Well, you could do something like:
var f = function() {
var $this = $(this);
if($this.hasClass('A')) { /* do something */ }
if($this.hasClass('B')) { /* do something else */ }
}
$('.selector').click(f);
and so inside the f function you check what was class of clicked element
and depending on that do what u wish
For better performance, you can assign only one event listener to your page. Then, use event.target to know which part was clicked and what to do.
I would put each action in a separate function, to keep code readable.
I would also recommend using a unique Id per clickable item you need.
$("body").click(function(event) {
switch(event.target.id) {
// call suitable action according to the id of clicked element
case 'dictionaryFlip':
flipDictionnary()
break;
case 'menuToggle':
toggleMenu()
break;
// other actions go here
}
});
function flipDictionnary() {
// code here
}
function toggleMenu() {
// code here
}
cf. Event Delegation with jQuery http://www.sitepoint.com/event-delegation-with-jquery/

Confused with calling JQuery custom function

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/

Jquery/Javascript target in function

I have a function that I am calling with two images like so.
$('#image1').bind('click',doNext);
$('#image2').bind('click',doNext);
I need to be able to tell which one called the function.
function doNext(){
if(target == $('#image1'){
alert('image1');
}else{
alert('image2');
}
}
this within doNext will be the raw DOM element, so:
function doNext() {
if (this.id === "image1") {
alert('image1');
}else{
alert('image2');
}
}
There I'm branching on the id because you specifically did that in your code, but usually you just interact with the object.
If you need to use any jQuery functions, wrap the raw DOM element in a jQuery object (var $this = $(this);), but you don't need to if all you want to do is look at the id as I did above.
Within jQuery event handlers, there are (at least) two significant DOM elements you have access to: The element on which you hooked the event (this), and the element that triggered the event (event.target). In your case, assuming that image1 and image2 are img elements, they'll be the same because img can't contain any other element, but in the case of elements that can contain other elements (div, p, etc. — e.g., most elements), event.target may be different from this. Say you have:
<div id="foo">
<p>Blah blah blah</p>
</div>
and this
$("#foo").click(function(event) {
alert(this.tagName);
alert(event.target.tagName);
});
If you click the paragraph, you'll get
DIV
P
...because you hooked the event on the div, but it was triggered by a click on the p. (This is the basis of event delegation.)
var id = $(this).attr('id');
if (id == 'image1') {
alert('image1');
} else{
alert('image2');
}
Use the attr() function to retrieve the ID of the element. Also, I would further simplify this by adding a common class to both images so that you can do this:
$('.myimages').click(function() {
if($(this).attr() == 'image1') {
alert('image1');
}
else {
alert('image2');
}
});
You can use event.target:
function doNext(event){
if($(event.target).attr('id') == 'image1'){
alert('image1');
}else{
alert('image2');
}
}
You can get the event.target in the event handler function:
function doNext(event) {
var target = event.target;
}
Alternatively, this will refer to the clicked element:
function doNext() {
var clickedID = this.id;
}
$(document).ready(function() {
$('#image1').click(function(){doNext('image1')});
$('#image2').click(function(){doNext('image2')});
});
doNext = function (target){
if(target == "image1"){
alert('image1');
}else{
alert('image2');
}
}

Categories