how to apply jquery hover for multiple elements - javascript

I have a jquery object being passed to my function. In the function I get to one of the sibling. Now how do I apply the .hover to both the objects in one call.
Thanks

Not sure I know exactly what you want to achieve, but something like this?
myObject.siblings('selector').andSelf().addClass('hover');
The selector depends on how you want to find your sibling. You may want to use something like next('selector') or prev('selector'), rather than siblings().
Update
If the second object is not something that can be chained off of the first object, by a simple selector (which you should be able to do if it's a sibling), there's a more general solution.
var jq1 = $('any set of elements');
var jq2 = $('any other set of elements');
var all = jq1.add(jq2);
This way, regardless of how you find jq1 or jq2, they'll be combined into the variable all. From here you can do
all.addClass('hover');
or
all.click();
Working example

Related

How to get the k-th element in a jQuery set ... AS A JQUERY ELEMENT

So I encounter this situation often and I want to figure out a better way of going about it. I using the naming convention prefixing my jQuery elements with $ so that I can distinguish them from DOM elements. For example, the following:
$pointers = $('#pointer-box div.pointer');
The problem with that is, if I want to get the 3rd in the result as a jQuery, I have to do
$($pointers[2])
which looks awkward. Unless there's a better way of doing this?
You can use .eq() jQuery method
$pointers = $('#pointer-box div.pointer');
var element=$pointers.eq(2);
Given a jQuery object that represents a set of DOM elements, the .eq()
method constructs a new jQuery object from one element within that
set. The supplied index identifies the position of this element in the
set.

Editing objects in jQuery

$(function(){
var z = document.body.children[0];
var x=$("li", z);
x.name="Johnny";
alert(x.prop(name));
});
x should be an object containing all the elements within the first ul in the body.
Regardless of what the object contains, I would like to add a property with a value, and then use the prop() method to show it - but that doesn't seem to work. Why is that?
I saw a script containing the following: var $x = $("div"); - Do I have to add $ to the variable name if it's a jQuery object?
To select the first ul element inside a page you can do:
$("ul:first li")
This way you are going to select all lines inside the first list in the page.
To store arbitrary data in an element you can use the method data, like this:
$("element").data('key', 'value');
and to retrieve the data:
$("element").data('key');
More info, for the data method.
If you really want to add an attribute you can use the attr method, it works the same way as the data method, but it would reflect in the DOM.
If you want all li elements in the first ul element, then this should do the trick:
var elements = $("ul:eq(0) li");
Here is a very simple example of this in action.
In regards to setting a property, you can do element.name = "test" and it will work ok. But what you need to understand is that this is setting a name property on the jquery collection object and NOT on any of the actual elements.
What you can do however, is set the property like so:
elements.prop("name", "test");
and the access it like so:
var name = elements.prop("name");//name will be "test"
Here is a working example
As I mentioned in my comment, you don't need to prefix the variable with $. But this can be helpful to easily see which variables are JQuery objects.
Number 1. x is a jQuery object, you added to that instance a name property, then you're using name though it wasn't defined.
If you want to change a property of the element you got with jQuery the ways are:
$('selector').prop('property', 'value');
$('selector').attr('attribute', 'value');
$('selector').get(index).property = "value";
Number 2. no you don't have to, $ prefix is simply a convention to make the code more readable.
Is there any specific reason behind using $ with variable in jQuery
Using the selector from #musefan answer, you can take the collection returned, and use the attr() method to add an attribute and value to each item selected. However, I've modified his selector slightly to actually grab "all" elements in there, (just in case future visitors wonder)
var elements = $("ul:eq(0)").children();
elements.attr("attrName", value);
So if you wanted to set the title:
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny");
You probably don't want to alert these values, browsers may ask you to stop allowing alerts on the page... but if you really did, then you could throw in an .each() after that.
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny").each(function(){
alert($(this).attr("title");
});

Adding onclick properties to each item in DOM object list in Javascript

I'm trying to move away from jQuery for my everyday site functionality, and I'm having a little bit of trouble with the onclick event. I'd like to put together a function like jQuery's .click(), but simply using document.getElementsByTagName and adding a func onclick won't work.
The question then is how would one add a single function to fire onclick to all elements in the list object returned by querying document.getElementsByTagName('h4')
EDIT: Just in case someone finds this and would like some code, here's what I did:
var headings = document.getElementsByTagName('h4')
for (var g in headings) {
headings[g].onclick = function() {
//code
}
}
You need to loop through the list and pass the event to each item.
I think there is no simpler way to do this, expect you need a library like jQuery or you write your own eventManager...

Combine jquery variables into one selector?

I'm looking for a way to combine jquery variables. Looking through related questions, nobody seems to be trying what I want to do.
$("body, div, p") is one method of combining by selectors, but after you assign a selector to a variable, how do you combine them in a similar fashion?
Here is one method I tried, but did not get it to work. I also tried putting them into an array (by simply adding brackets before $body and after $p).
$body = $("body");
$div = $("div");
$p = $("p");
$mixed = $($body, $div, $p);
// $mixed = $("body, div, p"); is NOT what I am looking for
In my actual script I've got some <select> inputs assigned to variables. I would like to put them into groups, so say I have a <select> which has "FRUIT" and another one that has "VEGETABLES", I could put them both into a jquery variable called "PRODUCE". Then if I need to perform anything on both of the two, I use produce instead.
...This might just be a stupid way to do things, though.
Perhaps you're looking for .add()?
$mixed = $body.add($div).add($p);
For me, it works fine in jQuery 1.10.2 to simply combine the elements in an array literal before passing into the jQuery constructor: $mixed = $([$body, $div, $p]);
I too was looking for something like this. In my case I had some objects passed into a common function and some created in memory and I wanted to apply the same click event to all of the objects. In the end I went with James's add solution above but thought I would share another option.
If you put the objects into an array you can use the each iterator to perform an action on them.
[$body, $div, $p].each(function(i,e) { e.DoSomething(); });
This syntax is longer and you don't get a reusable $mixed object, but there may be some scenarios where this is useful.

Most efficient way to re-use jQuery-selected elements

I can imagine the correct answer to this based on theory, but I'm just looking for some confirmation. I'm wondering what the most efficient way to re-use a jQuery-selected element is. For example:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
vs.
myDiv = $('#my_div');
myDiv.css('background','red');
//some other code
myDiv.attr('name','Red Div');
I assume the second example is more efficient because the element #my_div doesn't have to get found more than once. Is that correct?
Similarly, is it more efficient to first save $(this) in a varaible, such as 'obj', and then reuse 'obj' rather than using $(this) over and over? In this case, jQuery isn't being forced to find an element over and over again, but it IS being forced to convert this to a jQuery object [$(this)]. So as a general rule of thumb, should a jQuery object ALWAYS be stored in a variable if it will be used more than once?
You should write your code such that you limit the number of DOM traversals.
When you write something like this:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
You are finding #my_div twice, which is inefficient.
You can improve this either by assigning the result of a selector (i.e. var x = $('.something')) and manipulate the variable x, or you can chain your method calls like this:
$('#my_div').css('background','red').attr('name','Red Div');
You'll see the above code used a lot, because you're finding the element once. The css() method will apply a CSS style and return the actual result of $('#my_div'), so you can invoke another method, in this case attr().
My preferred way of handling the re-use of selectors is to store them as a variable, and wrap my stuff in a closure.
if you're using jQuery selector (like $('#element')), then yes, you should always store your results.
if you're using object and wrapping it in jQuery (like $(this)), it's not necessary, because jQuery doesn't need to search for that element again.
One thing that I find is generally overlooked is just how powerful jQuery chains are. It may not be so noticeable, but since jQuery caches your wrapped elements within a chain, you can modify elements, go into a more specific subset, modify, then go back up into a a general superset without much overhead.
I expect something like (pardon the example)
$('#myDiv')
.addClass('processing')
.find('#myInput')
.hide('slow')
.end()
.removeClass('processing')
;
to be better performance-wise than even
var $myDiv = $('#myDiv').addClass('processing');
var $myInput = $('#myDiv #myInput').hide('slow');
$myDiv.removeClass('processing');
This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.
$('a').click(function(){
var $this = $(this);
$this.addClass("clicked");
$this.attr("clicked", true);
});

Categories