Lets say I want to assign element's width to itself. For example, I have a div with content and I want to assign style="width:..." it.
Then in jQuery I do:
elem.width(elem.width());
Which looks for me totally wrong since it looks like how can I set the width by getting it..
Is there any better way to do it?
try this
document.getElementById('divName').style.width = '10px';
You can do this
$(function() {
$("#mainTable").width(100).height(200);
});
This has 2 changes, it now uses .width() and .height(), as well as runs the code on the document.ready event.
Without the $(function() { }) wrapper (or $(document).ready(function() { }) if you prefer), your element may not be present yet, so $("#mainTable") just wouldn't find anything to...well, do stuff to.
Better to add CSS using JQuery following way :
$(function() {
$("#test").css({
width : '30px',
height : '30px'
});
});
If you prefer the style, you could use jQuery's .css() method:
$('.element').css('width', $('.element').width());
If you have multiple elements with the same class (but different widths) you can do this:
$('.yourClass').width( function(id, width) {
return width;
});
See the docs for explanation.
Related
What I have:
I dynamically create a button and try to access the button width. In this example I'm doing console.log() but in my real case I want to use that value for other things.
let deleteButton = $(document.createElement("button"))
.addClass("deleteButton")
.text("delete")
.click(function() {
delete(this);
});
console.log($(deleteButton).width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The Problem:
Buttons have a width and height by default, but the console.log() shows zero.
How to get the default width and height of the button?
Observation: The most likely answer to be accepted is using .width() like functions of jquery or explain why that function is not working and show a better solution.
The function $.width() gets the current computed width for the first element in the set of matched elements.
Basically, that element wasn't rendered/processed by the engine, so the width is not available before it's added to the DOM tree.
let deleteButton = $(document.createElement("button"))
.addClass("deleteButton")
.text("delete")
.click(function() {
delete(this);
});
// Here the engine will render/process this element.
$(document.body).append(deleteButton);
console.log($(deleteButton).width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In jQuery, the css property of an element, can be returned using methods. One example is the width() method that returns the width of an element, like this:
$('div').click(function() {
alert($(this).width());
});
However, in vanilla JS, I tried the following code, but it returned null:
document.querySelector('div').onclick = function() {
alert(this.style.width);
}
How can I make it correct? I hope someone could help me with this.
Use getComputedStyle to get the width.
Here is a snippet
document.querySelector('div').onclick = function() {
var width = window.getComputedStyle(this,null).getPropertyValue("width");
alert(width);
}
DEMO
this here points to event object.you can it to the following
window.onload = function() {
document.querySelector('div').addEventListener('click', function(event) {
getWidth(event)
});
}
function getWidth(event) {
console.log(event.target.style.width);
}
<div style="width:300px">
hellow
</div>
Hope it helps
Similar question has been asked earlier, How to get an HTML element's style values in javascript?. The ans is as below, the answer also includes a sample code snippet to get css using JavaScript.
The element.style property lets you know only the CSS properties that
were defined as inline in that element (programmatically, or defined
in the style attribute of the element), you should get the computed
style.
I am trying to find all the elements with a specific background-image and change it to another one.
I tried doing it with this piexce of code:
jQuery('a').each( function() {
if ( jQuery(this).css('background-image') == 'url("someurl.png")' ) {
jQuery(this).css('background-image') == 'url("anotherurl.png")';
}
});
but it didn't work...any idea how can i do it??
since this is a really small page i would rather go threw all elements in the page...
there is a way to go threw all elements in page?
Change:
jQuery(this).css('background-image') == 'url("anotherurl.png")';
to:
jQuery(this).css('background-image','url("anotherurl.png")');
Setting a property with .css()
When setting values with jQuery's css(), you'd do
jQuery(this).css('background-image', 'url("anotherurl.png"))';
It's a function, not a property that can be set with =
You need to use the setter of css() to change the property. You can also use filter() and the instance of jQuery passed in to the document ready handler to keep the $ in use. Try this:
jQuery(function($) {
$('a').filter(function() {
return $(this).css('background-image') == 'url("someurl.png")';
}).css('background-image', 'url("anotherurl.png")');
});
I have an element div which is created by js, i want to get it class.
I try to getElementsByClassName('lt-label')(it works), than i want to check if lt-label has class lt-online and if it true the another block on the page is block.
My code:
$(document).ready(function() {
if (document.getElementsByClassName) {
var redTags = document.getElementsByClassName('lt-label');
if (redTags.is(".lt-online")) {
$("#l-b-wrapper").css({
'display': 'block'
});
};
};
});
But it doesn't work. Where i have mistake?
I give a link only because the html code is big and i can't show my problem full .Site http://www.zemelushka.ru/test/
lt-label - is a right page widget button
l-b-wrapper - left page widget button
You are mixing native and jQuery, Use jQuery object since document.getElementsByClassName will return you an array-like object and they don't have jQuery methods
$(document).ready(function() {
if ($('.lt-label').is(".lt-online")) {
$("#l-b-wrapper").css({
'display': 'block'
});
};
});
You have a really odd mix of native JS and jQuery which is causing the problem.
getElementsByClassName returns an array of DOMElements which do not have the is() method. If you use jQuery to select your elements you can both avoid the problem and shorten your code:
$(function() {
if ($('.lt-label').hasClass('.lt-online')) {
$("#l-b-wrapper").show();
}
});
Note that if there are multiple .lt-label elements found you may need to loop over them, depending on the behaviour you require.
To work with jquery methods you need jQuery Object otherwise you'll get error: method is undefined. So, you may also wrap javascript object with jquery like this:
if ($(redTags[0]).is(".lt-online")) {
Where, redTags is wrapped by jQuery ie. $() and we use [0] for first element as getElementsByClassName result array-like object.
But I would choose simply jQuery object while I work with jquery for simplicity:
$('.lt-label') instead of document.getElementsByClassName('lt-label');
As you should know jQuery has it's own dictionary of methods and it works only with jQuery objects. And you are trying to bind a jQuery method .is() to a dom object which causes in error because .is() is available only for jq objects.
So this would do it (creating a jq wrapper):
$(redTags).is(".lt-online")
and you can shorten it like:
$(document).ready(function() {
var redTags = $('.lt-label');
$("#l-b-wrapper").css({
'display': function(){
return redTags.is(".lt-online") ? "block" : "none";
}
});
});
If you just want to show/hide the element then you can use .toggle(boolean) method:
$(document).ready(function() {
var redTags = $('.lt-label');
$("#l-b-wrapper").toggle(redTags.is(".lt-online"));
});
I created a function in Jquery which is supposed to center elements vertically (I could not do it using css, got tired and just made it programically ^^). The problem now is that I initially created it using .each, and then, since it was already creator, I tried calling it using the selector ($('something').center), but it is behaving differently for some reason.
Using the selector, it seems to be doing just the same to every element. It does it with the first element, and then just applies all values to the remaining elements. So, for example, my function takes the element height and does some operations with it, but the selector just takes the first one and then applies its parameters to everyone..
I'll keep using each since it works best right now, but I still can't understand why they are doing that..
Centering Function:
$.fn.center = function (){
/*If this is the highest element, or
if this element has full use of the width,
then there's no need to align it.
*/
if(this.height() == this.parent().height() ||
this.width() == this.parent().width())
{
this.css({
position : "relative",
top : 0
});
}
else //Should be aligned.
{
this.css({
position : "relative",
top : (this.parent().height()/2)-(this.height()/2)
});
}
return this; //Used for chaining.
};
Here's an example of what I mean ^^
http://jsfiddle.net/lrojas94/pmbttrt2/1/
For simple things, like just changing the CSS in the same way for all elements with the same class, you can call it directly without using .each(). For example:
$('.elem').css('color', '#fff');
But if each of the divs needs to end up with an individual value, you should use .each(). For example (sorry it's a bit weird):
var border = 1;
$('.elem').each(function() {
$(this).css('border', border + 'px solid #000');
border += 1;
});
Basically, if you don't use .each(), it'll check what you want to change (just once!) and apply it to all elements with that class. If you do use .each(), it'll do it individually for each element.
Simply put, this within a jQuery plugin function is not a DOM node. It's the jQuery object that wraps around all the nodes that were matched by the selector.
Your function's body should rather look like:
return this.each(function () {
var $el = $(this);
//centering logic for $el goes here
});