What does data-toggle attributes do in Twitter Bootstrap? I couldn't find an answer in Bootstrap API.
I have seen a similar question before as well, link.
But it didn't help me much.
It is a Bootstrap data attribute that automatically hooks up the element to the type of widget it is. Data-* is part of the html5 spec, and data-toggle is specific to Bootstrap.
Some Examples:
data-toggle="modal"
data-toggle="collapse"
data-toggle="dropdown"
data-toggle="tab"
Go through the Bootstrap JavaScript docs and search for data-toggle and you will see it used in the code examples.
One working example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li>Item</li>
</ul>
</div>
Any attribute that starts with data- is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel and other attributes for purposes other than their original intended purposes (rel was often used to hold data for things like advanced tooltips).
In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).
html5doctor has a good article on the data- attribute.
Cycle 2 is another example of extensive use of the data- attribute.
For example, say you were creating a web application to list and display recipes. You might want your customers to be able to sort the list, display features of the recipes, and so on before they choose the recipe to open. In order to do this, you need to associate things like cooking time, primary ingredient, meal position, and so on right inside the list elements for the recipes.
<li>Borscht</li>
<li>Chocolate Mousse</li>
<li>Almond Radiccio Salad</li>
<li>Deviled Eggs</li>
In order to get that information into the page, you could do many different things. You could add comments to each LI element, you could add rel attributes to the list items, you could place all the recipes in separate folders based on time, meal, and ingredient (i.e. ). The solution that most developers took was to use class attributes to store information about the current element. This has several advantages:
You can store multiple classes on an element
The class names can be human readable
It’s easy to access classes with JavaScript (className)
The class is associated with the element it’s on
But there are some major drawbacks to this method:
You have to remember what the classes do. If you forget or a new developer takes over the project, the classes might be removed or changed without realizing that that affects how the application runs.
Classes are also used for styling with CSS, and you might duplicate CSS classes with data classes by mistake, ending up with strange styles on your live pages.
It’s more difficult to add on multiple data elements. If you have multiple data elements, you need to access them in some way with your JavaScript, either by the name of the class or the position in the class list. But it’s easy to mess up.
All the other methods I suggested had these problems as well as others. But since it was the only way to quickly and easily include data, that’s what we did.
HTML5 Data Attributes to the Rescue
HTML5 added a new type of attribute to any element—the custom data element (data-*). These are custom (denoted by the *) attributes that you can add to your HTML elements to define any type of data you want. They consist of two parts:
Attribute Name
This is the name of the attribute. It must be at least one lowercase character and have the prefix data-. For example: data-main-ingredient, data-cooking-time, data-meal. This is the name of your data.
Attribute Vaule
Like any other HTML attribute, you include the data itself in quotes separated by an equal sign. This data can be any string that is valid on a web page. For example: data-main-ingredient="chocolate".
You can then apply these data attributes to any HTML element you want. For example, you could define the information in the example list above:
<li data-main-ingredient="beets" data-cooking-time="1 hour" data-meal="dinner">Borscht</li>
<li data-main-ingredient="chocolate" data-cooking-time="30 minutes" data-meal="dessert">Chocolate Mousse</li>
<li data-main-ingredient="radiccio" data-cooking-time="20 minutes" data-meal="dinner">Almond Radiccio Salad</li>
<li data-main-ingredient="eggs" data-cooking-time="15 minutes" data-meal="appetizer">Deviled Eggs</li>
Once you have that information in your HTML, you will be able to access it with JavaScript and manipulate the page based on that data.
From the Bootstrap Docs:
<!--Activate a modal without writing JavaScript. Set data-toggle="modal" on a
controller element, like a button, along with a data-target="#foo" or href="#foo"
to target a specific modal to toggle.-->
<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>
So many answers have been given, but they don't get to the point. Let's fix this.
http://www.w3schools.com/bootstrap/bootstrap_ref_js_collapse.asp
To the point
Any attribute starting with data- is not parsed by the HTML5 parser.
Bootstrap uses the data-toggle attribute to create collapse functionality.
How to use: Only 2 Steps
Add class="collapse" to the element #A you want to collapse.
Add data-target="#A" and data-toggle="collapse".
Purpose: the data-toggle attribute allows us to create a control to collapse/expand a div (block) if we use Bootstrap.
The presence of this data-attribute tells Bootstrap to switch between visual or a logical states of another element on user interaction.
It is used to show modals, tab content, tooltips and popover menus as well as setting a pressed-state for a toggle-button. It is used in multiple ways without a clear documentation.
The purpose of data-toggle in bootstrap is so you can use jQuery to find all tags of a certain type. For example, you put data-toggle="popover" in all popover tags and then you can use a JQuery selector to find all those tags and run the popover() function to initialize them. You could just as well put class="myPopover" on the tag and use the .myPopover selector to do the same thing. The documentation is confusing, because it makes it appear that something special is going on with that attribute.
This
<div class="container">
<h3>Popover Example</h3>
Toggle popover1
Toggle popover2
</div>
<script>
$(document).ready(function(){
$('.myPop').popover();
});
</script>
works just fine.
It is a Bootstrap defined HTML5 data attribute. It binds a button to an event.
Here you can also find more examples for values that data-toggle can have assigned. Just visit the page and then CTRL+F to search for data-toggle.
Bootstrap leverages HTML5 standards in order to access DOM element attributes easily within javascript.
data-*
Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation that may be used by scripts. All such custom data are available via the HTMLElement interface of the element the attribute is set on. The HTMLElement.dataset property gives access to them.
Reference
Related
I am wondering if the html class attribute should only be used for styling. Is there any drawback to using the class attribute as a variable. The W3 spec http://www.w3.org/TR/html5/dom.html#classes does not specify one way or another but, all examples and training point in the direction of styling only for multiple objects.
In my case I want to use the class attribute as variable that matches the key value in a object array. For example in my Javascript code I have an object that has a number of key/value pairs. On my web app I have a number of save buttons. When a save button is clicked I grab the parents class attribute value and use it as the key for the object to know which value to change. The class attribute on the parent has not other value than to let me know which key value pair to change in my object
While I'm sure it's possible to use classes that way, it's certainly not their intended purpose. html has data attributes that provide the functionality you want, for example
<button data-key="some value" name="" id="">click me</button>
You can then get that value (onClick if you like) and use it as a key for your object/data structure. Theres a good overview here
While it is not bad, it neither is best practice.
You can, instead of using the class attribute, define explicit data attributes. Using the class attribute would mean that you could not use several classes (because that would be a weird key to search for in an object, right?).
For instance:
<div class="any classes you like" data-mykey="searchforthiskey">
<button></button>
</div>
In jQuery:
$('button').click(function() {
var key = $(this).closest('div').attr('data-mykey');
});
From a functional perspective, there's no reason to NOT use the class attribute to store information about that element. You can access a class attribute as easily as you can a data attribute.
From a standards perspective, it is probably better to use a data attribute. Why? Well, if you are the only person working on your front-end, no big deal. If you are one of many on a team of front-end developers, who works specifically on the javascript side of things, you may run into a conflict with another front-end developer who works on the HTML/CSS side of things. They may remove a class from the element, not realizing that its also being used as your javascript hook into that element. In that case, you're better off creating your own data attribute, which then makes it clear that this attribute is probably data related and won't be molested by someone just trying to fix the styling of that element.
In an out-of-the-box implementation of an MVC app using Bootstrap in Visual Studio 2013, there seems to be some javasvript that works on this element:
<li role="presentation" class="dropdown">
....
</li>
When that element is clicked, there is, somewhere, some JavaScript that changes the class in this element to:
<li role="presentation" class="dropdown open">
....
</li>
I want to augment/alter whatever script this is, but I can't find it. Or, I could also just create my own that works along side the existing script, but I can't figure out how to reference this element when it doesn't have an id. I'd rather not add my own id, as this list of li's is generated dynamically and I don't want to deal with referencing all the id's in the JavaScript.
How would I find the existing script that is making this change? OR How would I create my own script to handle the on-click?
Thanks!
You can reference the open li using css class selector '.':
$(".dropdown.open")
this will give you the currently open dropdown.
Explanation:
'CSS selectors' allow you to select elements using CSS syntax. For example:
'#id' where the '#' indicates the following text is the id of the element.
'.class' allows you to select all elements by class, eg $(".dropdown") gives you all elements with class "dropdown". These can be combined ".dropdown.open" - all elements with both class dropdown and open
Never change the library directly, there's an event you can hook into:
$('#id_of_ul').on('shown.bs.dropdown', function () {
// do something...
})
http://getbootstrap.com/javascript/#dropdowns
Explanation:
.on is the jquery event hook to provide your own handler when something happens, eg: $("#id").on('click', function....
In this case, the event is called shown.bs.dropdown and is provided / raised by the twitter-bootstrap dropdown functionality.
To answer the explicit question of where to find the scripts, you can download from getbootstrap.com or, they'll be in your MVC project under Scripts\
Assuming I have the following markup
<div data-common-notcommon="anyValue">
<!-- Whatever.. -->
</div>
<div data-common-not-commonerthing="anyValue">
<!-- Whatever.. -->
</div>
I'm trying to write a JS selector (or a CSS selector, don't care for the difference..) to find attributes based on a common, partial attribute name.
I.E I want to find all the elements that start with data-common.
I can't find anything on Google for attribute name selectors but rather attribute value selectors which I don't really want to do.
<script>
document.querySelectorAll('[data-common]'); // []
document.querySelectorAll('[data-common*]'); // []
// etc..
</script>
Currently there are no selectors defined to partially match attribute names. What you're asking for doesn't exist.
For JavaScript you could filter a collection of elements using custom code (that is what jQuery does), but it will not work with document.querySelectorAll, nor can you define a custom selector for CSS, unless you're willing to suggest it on the w3c mailing list and deal with navigating the complex workflow that's involved in changing the CSS language.
I have some bullet points which I want to show more text below them on clicking them. They are both two separate Ps that are paired together by sharing a common id. So, what I am trying to do below is to find the element with (id_same_as_this.class), so that the element with the class "expand" as well as the id that matches the clicked on P is toggled. Does that make sense?
$(document).ready(function(){
$(".expandable").click(function(){
$(this.attr('id')+"."+"expand").toggle(800);
});
});
I only ask if the above code could be made to work because it would make the expandable bullet points in my web page significantly less code intensive than a lot of the examples I have read about.
$(this.attr('id')+"."+"expand").toggle(800);
Must be
$("#" + this.id +".expand").toggle(800);
You missed the # there. That said, you shouldn't ever have a common ID. By definition IDs are meant to be unique. If you have the same ID on multiple elements, while it may work now on the browsers you try, you have no guarantee it won't break in the next rev of jQuery (or Chrome, or Konqueror, or iOS Safari). There's also no reason to do it. You could just use classes or data-* attributes.
Yes this will work but you need a # before the ID
They are both two separate Ps that are paired together by sharing a common id.
IDs are unique. Two elements can't share a common ID, as that defeats the whole purpose of having a unique identifier. JavaScript assumes that you're using valid HTML, so document.getElementById() will return only the first element with a matching id. By using non-unique IDs, things will start breaking in unpredictable ways:
$('#foo').find('.bar') // Won't search past first #foo
$('#foo .bar') // Will search past first #foo in IE8+
Try restructuring your HTML to make this task easier. Maybe you could do something like this:
<ul id="bullets">
<li>
<h2>Title</div>
<div>Text</div>
</li>
</ul>
And then use a simple event handler:
$('#bullets h2').click(function() {
$(this).next().toggle(800);
});
You don't need id values for this at all (which is good, as from the comments on hungerpain's answer, you're using the same id value on more than one element, which is invalid).
Just do this:
$(document).ready(function(){
$(".expandable").click(function(){
$(this).find(".expand").toggle(800);
});
});
That will find the element with the class expand within the expandable that was clicked. No relying on unspecified behavior of selectors.
If you really need that data on the expandable, just put it in a data-* attribute. So instead of this invalid structure:
<!-- INVALID -->
<div id="foo27" class="expandable">
<div class="expand">...</div>
</div>
<div id="foo27" class="expandable">
<div class="expand">...</div>
</div>
Do this
<!-- VALID -->
<div data-id="foo27" class="expandable">
<div class="expand">...</div>
</div>
<div data-id="foo27" class="expandable">
<div class="expand">...</div>
</div>
Use the above code to do the expansion. If you need the value, use .attr("data-id") or .data("id") to get it.
During the web development i encountered with many problems and resolved it but these problems gave me a thought which i want to share and would like to know your view.
Which One is efficient Class Or ID : Both has own specification but i think Class is more convenient over ID (if you are dealing with thousands of IDs.)
I know Id is quite efficient for DOM Traversing but what if you have hundreds of elements with IDs, How do you manage ?
Using CLASS : One class can be derived by many elements and the individual elements can be dealt by using "this" object.
I am curious to know your view OR how do you handle the project/projects when you have many-many elements with ID or Class name
<div class="example" onclick="function click(this);"> </div>
<div class="example" onclick="function click(this);"> </div>
<div class="example" onclick="function click(this);"> </div>
function click(obj){
alert(obj.classname + "We can access any individual element by using Object");
}
<div id="exm_1"> </div>
<div id="exm_2"> </div>
<div id="exm_3"> </div>
but in case of ID, we go through each ID
I liked a few guidelines that are put together by one of my managers, I would like to mention them here:
Start with the following common sense guidelines, and apply them to both JavaScript selectors and CSS selectors.
Use an ID if:
You are certain that the element only
appears once in the whole page.
The desired style or JS behavior is
specific to only one area of the
whole page.
Typical ID Examples:
Large container divs for entire
sections of the page ("#interior",
"#global-status", "#tree-container")
Links or buttons with special names
and purposes ("#add-new-report",
"#preview-popup")
Use a class if:
It is possible for the element to
appear multiple times in the same
document.
The desired style or JS
behavior is general and is applicable
to multiple elements.
Typical Class Examples:
Reusable interface patterns
(".action-links", ".title-bar",
".h1-with-border")
Element states
(".current-selected", ".highlighted")
You should follow this general guidelines:
2) Use a class when you need many elements to share some common behaviour, or when there's currently only one element but you're not sure if there will be more with the same behaviour in the future.
1) Use an Id when an element needs unique identification and you're sure there will be only one with it (think in the future code changes). There should never, never be 2 or more elements with the same id.
Hope this helps. Cheers