How can I make a function for one element, like the each() does it for multiple elements?
What I want to do, (just for the sake of the example)
$(".element").each(function () {
var height = $(this).height();
$(this).css("bottom", "-" + height + "px");
});
Should I just use the Each() or should I use one()?
Just call the .css function if you only want to do it once. You can pass an anonymous function as the second paramter in order to do what you're trying to do.
Just remember that this will still do the action to every element that matches your selector. If you only want to apply this to one element, you need to be more specific with your selector.
$(".element").css("bottom", function() {
return "-" + $(this).height() + "px");
});
each() will works fine also for collections with one element only, but in this case it is not really necessary and for one element introduces only overhead so it's better simply write
var height = $(".element").height();
$(".element").css("bottom", "-" + height + "px");
also note that one() is not an alternative because its purpose is to attach an handler that has to be called one time only
jQuery each will work perfectly with just the one element in it. So you can go ahead and use .each safely
like this?
$(".element").css("bottom", "-" + $(this).height() + "px");
It doesn't need to be in a function
Related
I have 3 blocks of images with text on top of them. Here is how one of the 3 looks like.
<div class="lp">
<h2 class="align-vert">
This is my title
</h2>
</div>
I want to get the title height(); in jQuery and apply it to the aligh-v. I tried the following jQuery code but it doesn't work.
jQuery.each(jQuery('.js-vert'), function() {
jQuery(this).css({
"margin-top": '"' + jQuery('.js-vert').height() + '"'
});
});
The issue is because you need to use the this reference within the each() method to refer to the current element. As it stands, your code is calling height() the entire set of elements which means only the height of the first element is returned. Your syntax of string concatenation is also a little off. Try this:
$('.js-vert').each(function() {
$(this).css("margin-top", $(this).height());
});
Also note that this can be made more succinct by removing the each() loop entirely and passing a function to the css() method which returns the value needed:
$('.js-vert').css('margin-top', function() {
return $(this).height();
});
I have a jQuery selector which I am using to apply a tooltip to an element:
TooltipBuilder.buildRackDisplayTooltip(this.$el, rackInformationListView.render().$el);
My element does not have an id. It does not need one because this.$el uniquely identifies the element.
I would like to modify my statement such that the selector now matches two elements:
// Doesn't work
var selector = this.$el + this.$el.children('.rackName');
I am hoping to trigger a mouseout event only when the mouse leaves this.$el or when the mouse enters some, but not all, descendants of this.$el
Is it possible to create such an expression without assigning an id to this.$el?
If my element had an id, I might use a selector such as:
var selector = $('#' + this.el.id + ' ,' + this.el.id + ' > .rackName');
although this still seems unnecessarily verbose
You can combine the elements(probably your variable says selector) using add
var selector = this.$el.add(this.$el.children('.rackName'));
You can even provide just selector strings to add as well.
var selector = this.$el.add('someselector');
And to add on for just in the first example, where you are trying to get the children and add parent to it. You can use var selector = this.$el.children('.rackName').addBack();, second example you can use .add() for distinct selectors.
I've seen this a bunch:
Click me
<div id="content">And something will happen here</div>
With JS like this:
$("#trigger").click(function(){
$("#" + $(this).data("target")).hide();
})
It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?
Why you do string concatenation just store the id with #
Click me
$("#trigger").click(function(){
$($(this).data("target")).hide();
})
Similarly you can store any selectors as is in data-target say for ex:- .tab1 etc so that you do not have to perform string concatenation again inside the click or any event.
You can simply use
$('#content').modal('toggle');
Any where in you're code to initiate the modal show and hide,
You can use even "show"/"hide" functionality directly.
I assume you're using Bootstrap and one of the latest versions of jQuery.
Enjoy !
Why not do something like this, a much better approach in my opinion:
// Set the target
$("#trigger").data('target', $('#content'));
// Get the target
$("#trigger").click(function(){
$(this).data("target").hide();
})
If you're setting it from the backend, I would include the hash with the attribute value as others have suggested.
Click me
$("#trigger").click(function(){
var target = $(this).data("target");
$(target).hide();
})
You always have the option to build the selector, looks a bit nicer than concatenating the string inside the selector.
$("#trigger").click(function(){
var selector = "#" + $(this).data("target");
$(selector).hide();
});
A little nicer, not sure if it's what you're looking for.
I would skip the data- completely, thus allowing graceful degradation.
Click me
<div id="content">And something will happen here</div>
with
$("#trigger").click(function(e){
e.preventDefault();
$( $(this).attr("href") ).show();
// note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash
})
$(this).attr('data-target', '#myTarget');
this worked for me
I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});
I'm trying to build a sticky note with Javascript and jQuery. The problem I am having is, that the functions draggable() and deleteNote() can not be called on the newly appended elements. How can I fix this?
EDIT: The ID actually should get an added number, which I'm not sure how to implement, because I don't know how to create a counter. E.g. newbox1
My code on jsfiddle: http://jsfiddle.net/wowpatrick/qexRS/4/
You need to attach the eventhandlers live, since there are no elements existent at the moment you initially called them.
Use jQuerys live() (Attention:deprecated Docu) or with new jQuery-version on() (Docu), to be able to attach the events on each newly created note.
Also don't use IDs, since this produces invalid markup because IDs always have to be unique. Use classes instead.
You could add the .click handlers to the new element after you create it.
You shouldn’t create multiple elements with the same ID, use class instead.
Also, you can attach the .draggable() to the created element right away instead of targeting $('#newbox').
Here is a fork that works better: http://jsfiddle.net/YvtLb/
The key is here:
var postit = $('<div class="ui-widget-content newbox" style="top:' + e.pageY + 'px; left: ' + e.pageX + 'px;"><span id="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>').draggable();
$('#canvas').append(postit);
This is because on page load #newbox does not exist. A better method would be to store your new element in a variable, append it, then apply draggable, try this:
// Create the new comment at the corsor postition
var $newbox = $('<div class="ui-widget-content" id="newbox" style="top:' + e.pageY + 'px; left: ' + e.pageX + 'px;"><span id="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>');
$('#canvas').append($newbox);
$newbox.draggable();
Example fiddle