I have set a data attrabute called "sel", and the following jQuery asks for the data-sel that has a value of 'true', but it's adding it to every class, even the ones that don't have 'data-sel'
jQuery:
var selTrue = $(".slide").data("sel", 'true');
$(selTrue).css({'display': 'inline-block'});
HTML:
<div class='slide' data-sel='true'>1</div>
<div class='slide' data-sel='true'>2</div>
<div class='slide'>3</div>
<div class='slide'>4</div>
How do I prevent if from applying to to every class?
Trying to solve:
• I tried this:
$(".slide").not(selTrue).css({'display': 'none'});
still didn't solve my problem
Fiddle
In order to select against your data attribute you need to use
$(".slide[data-sel='true']").css({'display': 'inline-block'});
what you're doing is actually selecting all elements with the slide class, and then setting their data-sel attribute.
here's the documentation
http://api.jquery.com/attribute-equals-selector/
$(".slide").each(function () {
if ($(this).data("sel") === true) {
$(this).css({'display': 'inline-block'});
}
});
You are setting the data-sel attribute to true with
$(".slide").data("sel", 'true');
var selTrue = $(".slide").data("sel", 'true');
What that does is fetch all divs with class "slide" and set the value 'true' for key 'sel' on them. So selTrue is a jQuery array of all divs with class .slide. And then you are setting display: inline-block for all elements in the array (the 4 divs on the page).
What you want to do is :
$('.slide[data-sel = "true"]').css('display', 'inline-block')
The square brackets indicate a query based on an attribute.
Related
I have a simple block of code to hide/show two divs. It works great, the only issue I have is that I need to return the display value to the #MSOZoneCell_WebPartWPQ2 back to table. I have set it to none in the css initially. The last line doesn't seem to take effect.
here is the code:
$(function() {
$('#swap').click(function() {
$('#MSOZoneCell_WebPartWPQ2').toggle();
$('#example_wrapper').toggle();
$('#MSOZoneCell_WebPartWPQ').css('display') == 'table';
});
});
You're using == operator
Try this:
$(document).ready(function(){
$('#swap').click(function() {
$('#MSOZoneCell_WebPartWPQ2').toggle();
$('#example_wrapper').toggle();
$('#MSOZoneCell_WebPartWPQ').attr('style','display:table;');
});
});
you should use .css( propertyName, value )
Set one or more CSS properties for the set of matched elements.
so your last line should be
$('#MSOZoneCell_WebPartWPQ').css('display', 'table');
when you call .css( propertyName )
$('#MSOZoneCell_WebPartWPQ').css('display);
you are Getting the value of said property not setting it
Get the computed style properties for the first element in the set of
matched elements.
Update 1:
please note that Jquery's .show(), .hide() and .toggle() will only work with elements with block display property.
so one way to avoid changing the display property back and forth is to wrap the wanted elements in a div (container) and .toggle() it.
I have created a JSFiddle, I warped each div in a container div with a calss called "toggle" and set initial display value of one of them to "none" using style attribute.
<div class="toggle" style="display:none">
now I toggle between them using this
$('.toggle').toggle();
Update 2:
you can also use .toggleClass() here's another JSFiddle
Add this to your CSS
#example_wrapper.hiddenDiv, #MSOZoneCell_WebPartWPQ2.hiddenDiv {
display: none;
}
add a class to the div you want initially hidden
<div id="MSOZoneCell_WebPartWPQ2" class="hiddenDiv">
toggle the class using this
$(function() {
$('#swap').click(function() {
$('#MSOZoneCell_WebPartWPQ2').toggleClass("hiddenDiv");
$('#example_wrapper').toggleClass("hiddenDiv");
});
});
in this example I'm using a class called "hiddenDiv", if you change it make sure the class name is the same in CSS, HTML and JS.
you are sure you need "==" to set the value? or one "="
Firstly == is an equality check. You should use = to set a value.
Secondly, the css() method setter accepts two parameters. The rule to set and the value itself. Try this:
$('#MSOZoneCell_WebPartWPQ').css('display', 'table');
I'm working on adding specific data- attributes to my slideshow so I can add custom backgrounds for each slide. What I do is add the custom data attribute, then assign the value to a variable using jQuery. After that, I pass the variable to the .css() and assign it to the background property.
var elementSection = $(".cycle-slideshow section")),
sectionBackground = elementSection.attr("data-cycle-slide-background");
$(elementSection).css({background: sectionBackground});
<section data-cycle-slide-background="url(images/slides/laptopgreenery.jpg)"></section>
<section data-cycle-slide-background="url(images/slides/slide1bg.jpg)"></section>
<section data-cycle-slide-background="url(images/slides/slide2bg.png) repeat;" data-cycle-hash="2"></section>
However, doing it this way sets every slide's background to the one in the attribute, in this case "laptopgreenery.jpg".
You should loop over each slide:
elementSection.each(function() {
$(this).css('background', $(this).data('cycle-slide-background'));
});
Important: make sure you don't have ; at the end of data attributes, it will make rule invalid and it will not be applied.
Demo: http://jsfiddle.net/vetnLr8n/
You can taked advantage of the anonymous function available to the css() method; inside of which `$(this) refers to the current slide):
$(elementSection)
.css({
background: function() {
return $(this).data('cycle-slide-background');
}
});
I'm trying to build a box container that expands when clicking in a "read more" button and collapse to the initial size when clicking in the same button (now a "collapse" button).
In the DOM I have a .leer-mas button inside a .post container. And the following jQuery code:
//When link with class .leer-mas is clicked, get the parent element's id and add some css attributes
$('.leer-mas').click(function() {
var item = $(this).closest('.post');
item.css('height', 'auto');
$(this).addClass('leer-menos');
$(this).text('Leer menos');
});
//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$('.leer-mas.leer-menos').click(function() {
var item = $(this).closest('.post');
item.removeAttr('height');
$(this).removeClass('leer-menos');
})
The first action works like a charm. But the second action does nothing... And I think I'm missing some fundamentals of jQuery, as the syntax is identical and maybe that is not the way it should be :)
Any ideas? Thanks.
Edit - I had a few errors on my code. Though I'm still trying to get it with a single switcher, I have a working version.
New DOM looks like this:
<div class="post">
<div class="leer mas">
</div>
<div class="leer menos">
</div>
</div>
The code now looks like this:
//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.mas').click(function() {
var item = $(this).closest('.post');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
item.css('height', 'auto');
$(this).hide();
$(this).next('.leer.menos').show();
});
//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.menos').click(function() {
var item = $(this).closest('.post');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
item.removeAttr('style');
$(this).hide();
$(this).prev('.leer.mas').show();
});
This works smoothly. But If I get it working with the intended structure of the original question (with a single button), i would be happier :)
it is because the class leer-menos is added dynamically... so when the event registration code is executed there is no element with classes leer-mas and leer-menos.
A possible solution is to use event delegation
//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$(document).on('click', '.leer-mas.leer-menos', function() {
var item = $(this).closest('.post');
item.removeAttr('height');
$(this).removeClass('leer-menos');
})
You're trying to use .removeAttr() to remove a CSS Property within the attribute "Style". This is incorrect, try using item.removeAttr('style');
Not exactly what you asked for, but you can draw ideas from this:
$('.leer-mas').click(function() {
var item = $(this).closest('.post');
// toggle "height" between 'auto' and null
item.css('height', item.css('height') == 'auto' ? null : 'auto' );
// toggle class 'leer-menos'
$(this).toggleClass('leer-menos');
// toggle text between 'Leer menos' and ''
$(this).text( $(this).is('.leer-menos') ? 'Leer menos' : '' );
});
I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here's a sample HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
So, I need to take that and turn it into this:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
How do you locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
Live demo: http://jsfiddle.net/phbU9/
The attributes property returns a list of all attributes set on the element. "Naked" elements have an empty attributes list.
Update: Be sure to read Tim's answer below which provides a solution for older versions of IE, since my own solution doesn't work in IE8 and below.
#Šime's answer is close but doesn't work in IE 6, 7 or 8, where an element's attributes collection has an entry for every possible attribute, not just those specified in the HTML. You can get round this by checking each attribute object's specified property.
Live demo: http://jsfiddle.net/timdown/6MqmK/1/
Code:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
check this out:
http://jsfiddle.net/thilakar/CHux9/
You need to give some sort of selector, in this case Ive used your side bar but it can be anything. Then get the children that have no class attribute and add a new class. See JSFiddle for the example:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
So this would return the 2 elements with no class tag and leave the sidebar and div with the class completely unaffected.
You could use a combination of jQuery's has attribute selector and the not selector. For example:
$('div:not([class], [id])').addClass('myClass');
jsFiddle demonstrating this
With this approach, you need to explicitly specify the attributes to check the presence of. Sime's solution would apply the class to divs that do not have any attributes at all.
To expound upon Tim Down's answer, I recommend checking that the attrs var not null special cases where the html has comment tags, etc.
try $('div:not([class])').addClass('myClass');
it is a general approach because the class will apply to all the div that have no class
$('#sidebar div')` or more general `$('div'); //returns collections of divs
to answer the question:
$('#sidebar div').addClass('myClass');
I need some help in adding a tabindex to all the elements in a <div> dynamically. I need to do this for accessibility. If I specify a <div> element, it should automatically add the tabindex to all elements in that <div>.
I tried some thing like this:
$('#Latest-News-Content [tabindex]').each(function () {
$(this).attr( 'tabindex', parseInt( $(this).attr('tabindex') ) + 10 )
});
but it doesn't seem to work. Also, how can I add a tab index for elements which are hidden?
For example:
I have a title and description showing in a <div>. The description is hidden and has a jQuery collapser. When I click on the title the description expands. How can I set a tabindex for all the elements?
Here an example that adds tabindex for all a tags
$('#Latest-News-Content a').each(function(index) {
$(this).attr('tabindex', index)
});
Demo: http://jsfiddle.net/azk2n/1
You can use the same method for hidden elements.
#Sotiris
This might be an update with newer versions of jQuery. Use .prop() instead of .attr() to set property values.
$('#Latest-News-Content a').each(function(index) {
$(this).prop('tabindex', index)
});