add attribute to DOM element - javascript

I have a modal form that is generated using bootstrap 3. It doesn't look like there is a reliable way to determine when that form is being shown onscreen. I am attempting to create one. I attached two events to my DOM element that signal when it is shown and when it is hidden.
jq_modal_login_form = $('#modal-login-form')[0]
jq_modal_login_form.on('shown.bs.modal', function () {
jq_modal_login_form.active_onscreen = true;
});
jq_modal_login_form.on('hidden.bs.modal', function () {
jq_modal_login_form.active_onscreen = false;
});
I tried to give an attribute named active_onscreen to the DOM element above. When I look at the DOM element in the debugger later, the attribute is not present.
I should mention that I am VERY new to javascript. Is attribute even the right word to use here? It looks like attribute is a bit of a misnomer as well. It could be an attribute of the object but could also be an attribute of the object.attributes attribute, right? I assume the later is where styling ect., goes and is not what I want to change. Does anyone have some insight as to what I should be doing here?

In jQuery:
$('selector').attr('attribute_name', 'value');
However, you can should only use predefined attributes as creating custom attributes requires additional setup (see this question) that is not necessary in your case.
In your case, you may just want to add a active_onscreen class to the element. Classes are meant to be used to identify elements (and not just for CSS), so they are perfect for this applicaiton. You would use this to add a class to an element:
$('selector').addClass('active_onscreen').
When it is no longer active, you would use this to remove the class:
$('selector').removeClass('active_onscreen').

What you are doing here is adding a property of the DOM object - not an attribute of the element.
Adding an attribute does not necessarily make the property mirror it. Only built-in properties do this.
If you want to set an attribute, but not the property, you can use jQuery's .attr() method.

If you just want to see if a given modal is open, Bootstrap does that for you. You can check the bs.modal data attribute:
$("element").data('bs.modal').isShown;
or a class (but this method is prone to race conditions):
$('#myModal').hasClass('in');

Related

All elements of same name, added dynamically, with on click handler all fire when referred by class name but different data-attribute

Lets say I add an element to the dom using jquery, with an onclick handler with a class=“justice” and data-attribute = “1", and then add another element with the same class name, but different data-attribute = “2”, also lets say I gave both elements different values. I should be able to just call $(‘.justice[data-attribute=‘2’]“).val, which would be different than $(‘.justice[data-attribute=‘1’]“).val right?
Yes you should. In your example though, you did not use a period when selecting the class.
Also, do not forget the parentheses following the val call per the jQuery spec.
$(‘justice[data-attribute=‘1’]“).val
VS.
$(".justice[data-attribute='1']").val()

JQuery keyword "this" does not get attribute value

I am playing around with the JQuery keyword this.
I have come across something I do not understand.
Here is my code:
<body>
<a id="link_1">jQuery.com</a>
<!-- adding JQUERY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my JavaScript -->
<script>
$("a").attr("href", "target_1");
$("a").attr("new_attribute", "new_attribute_value");
$(function ($) {
$("a").mouseenter(function(){
alert(this.id);
alert(this.href);
alert(this.new_attribute);
});
});
</script>
</body>
I want JQuery to return the id, href and my new_attribute as an alert message.
I can call the id on the keyword 'this' (with this.id) and it works as expected.
I can also call the href on the keyword this (with this.href) and it works as expected (even though I set the value of href with JQuery only (an not inline)).
However with the new attribute "new_attribute" this kind of set & get does not work as expected.
my question: What am I doing wrong? Is it only possible to call 'certain /limited' attributes on the keyword 'this'.
It's because new_attribute is not a valid attribute.
Some built in attributes are mapped to properties, and when you do
this.id
you're really getting the id property, not the attribute, as that would be
this.getAttribute('id')
you could do
this.getAttribute('new_attribute')
but you should really be using data-* attributes, and not make up your own, but jQuery's data() maps data internally and doesn't add attributes, but in your case that's probably what you want, just store arbitrary data on the element
$("a").attr("href", "target_1");
$("a").data("new_attribute", "new_attribute_value");
$(function ($) {
$("a").mouseenter(function(){
alert(this.id);
alert(this.href);
alert( $(this).data('new_attribute') );
});
});
In this context this points to HTMLAnchorElement object, and the problem here is the difference between HTMLElement attributes and their properties. Simply saying, attributes are rendered as a part of HTML, and used for additional object declarative configuration from the side of HTML markup.
On the other hand, there are properties of the object, which not always have corresponding attributes. Sometimes they do, but in most cases - they don't.
You can set any arbitrary attribute to HTMLElement like you did with new_attribute, but this custom attribute value will not become an object property. So reading such custom attribute as property will yield undefined.
"this" refers to the DOM element (try console.log(this)). An Element exposes its id attribute, as you can see here : https://developer.mozilla.org/en-US/docs/Web/API/element
Since it is an A element, it also exposes its href attribute. But it never knows your custom attribute. So it can't expose it.
Try this in you event handler :
var $this = $(this);
alert($this.attr('new_attribute'));
You need to treat this as a selector, so write it like $(this)
Your problem is that you set an attribute with the attr() method but you're querying (getting) it with a call to an equivalent method to jQuery'sprop().
Since this is a non standard attribute, the main interface for the anchor <a> element HTMLAnchorElement or other interfaces that it inherits from in the DOM don't have/implement a new_attribute property in place, your this.new_attribute would always return undefined.
However, if you'd like to keep experimenting with the this keyword, you could try something along these lines this.attributes['new_attribute']and you won't have any unpleasant surprises in your coding excursion anymore :)

How to reset the field style in jQuery-Form-Validator?

I'd like to reset the style any element in jQuery-Form-Validator.
I've seen that the next following is used to do it:
$('#exportMapForm').get(0).reset();
But the only thing that has been removed is the data and not its style.
The .reset() function removes the data and does not alter the style. To access the style of a particular DOM node (which in your case, looks like $('#exportMapForm')) you can use something like
$('#exportMapForm').className = '.myResetStyleClass';
Also, since the hash/pound symbol is an ID selector, and there should only ever be one element with that particular ID, there is no need for .get(0) after $('#exportMapForm').
UPDATE:
Finally I could to solved it and the answer was writting by #ChristynCanada Link to Answer
Basically, we need to add the following code:
// To register all properties the `form` before resetting
form('exportMapForm').registerReset();
// Reset
form('exportMapForm').Reset();

What is the difference between removeProp and removeAttr in JQuery 1.6?

If you removeProp on something you should have used removeAttr() on will it silently fail? Will it work? Will it actually remove the entire attribute or just the value inside it?
If checked is added using removeProp(), can it be removed with removeAttr()?
Many questions!
The official jQuery blog provides a very clear explanation:
In the 1.6 release we’ve split apart
the handling of DOM attributes and DOM
properties into separate methods. The
new .prop() method sets or gets
properties on DOM elements, and
.removeProp() removes properties. In
the past, jQuery has not drawn a clear
line between properties and
attributes. Generally, DOM attributes
represent the state of DOM information
as retrieved from the document, such
as the value attribute in the markup
. DOM
properties represent the dynamic state
of the document; for example if the
user clicks in the input element above
and types def the .prop("value") is
abcdef but the .attr("value") remains
abc.
In most cases, the browser treats the
attribute value as the starting value
for the property, but Boolean
attributes such as checked or disabled
have unusual semantics.
For example, consider the markup
<input type="checkbox" checked>. The
presence of the checked attribute
means that the DOM .checked property
is true, even though the attribute
does not have a value. In the code
above, the checked attribute value is
an empty string (or undefined if no
attribute was specified) but the
checked property value is true.
Before jQuery 1.6, .attr("checked")
returned the Boolean property value
(true) but as of jQuery 1.6 it returns
the actual value of the attribute (an
empty string), which doesn’t change
when the user clicks the checkbox to
change its state.
There are several alternatives for
checking the currently-checked state
of a checkbox. The best and most
performant is to use the DOM property
directly, as in this.checked inside an
event handler when this references the
element that was clicked. In code that
uses jQuery 1.6 or newer, the new
method $(this).prop("checked")
retrieves the same value as
this.checked and is relatively fast.
Finally, the expression
$(this).is(":checked") works for all
versions of jQuery.
An attribute of an element is something like 'class'. Whereas its property would be 'className'.
This is the reason for adding jQuery.prop and jQuery.propHooks into version 1.6, to make it easier working with both.
So if the the property had the same name as the attribute you could use both removeProp or removeAttr.
I asked a similar question on jQuery forum, got this answer:
Yes, attr is meant for html attributes
as they are strictly defined. prop is
for properties. So for instance, say
you have a node elem with class
"something" (raw element not jQuery
object). elem.className is the
property, but is where the
attribute resides. Changing the class
attribute also changes the property
automatically and vise versa.
Currently, attr is jumbled and
confusing because it has tried to the
job of both functions and there are
many bugs because of that. The
introduction of jQuery.fn.prop will
solve several blockers, separate code
as it should have been separated from
the beginning, and give developers
faster functions to do what they
expect them to do. Let me make up a
percentage for a sec and say that from
my experience in the support IRC and
reading other's code, 95% of the use
cases for attr will not have to switch
to prop.
EDIT
It may be best to stick to using either jQuery.attr or jQuery.prop. Theres seems to be some strange behaviour when setting and removing the checked attribute using both.
See here for an example: http://jsfiddle.net/tomgrohl/uTCJF/
There is a bug in 1.6 to do with selected: http://bugs.jquery.com/ticket/9079
Using jQuery 1.6, I was was trying to clone a menu item which had several id attributes, and so I did this:
$('ul.menu').clone().filter('*').removeProp('id').appendTo('.sidebar');
When I inspected the elements in Firebug I had a lot of id="undefined" - not what I wanted. So now I am using removeAttr and it seems to work much better.
$('ul.menu').clone().filter('*').removeAttr('id').appendTo('.sidebar');

Stick ID to the HTML element (using js) instead of id-attribute?

First post on stackoverflow. Hope everything is right!
I'm thinking of attaching an ID value to the HTML element itself via JavaScript, instead of using the HTML id attribute.
For instance, say that JavaScript variable htmlElement is a div. So htmlElement.cssName would tell us its CSS class.
Now, how about doing
htmlElement.idProperty = "someValue"
in JavaScript instead of doing <div id="someValue">? Then I can use the idProperty in say event handlers.
this.idProperty
That simple!
Is there something wrong in doing so?
EDIT: Thanks for yor answers! Very helpful and instructive. I wish I could check green on all of them!
no, you can do it the way you like it, if you are dynamically creating this item you should use this method, if you are doing this inside html I recommend you to just put the name of the id in html too.
However a small note. Use element.id instead of idProperty.
element.id = 'my-id';
You can use the createAttribute method to add an id to the element like this:
id = document.createAttribute('id');
id.value = "someValue";
htmlElement.setAttributeNode(id);
What you're doing there is adding a runtime property (in your case, called idProperty) to an HTMLElement object instance. You can get away with doing that in your JavaScript code (the Prototype library does it all the time). Makes me uncomfortable, but it does work on all major browsers.
If you want to be able to specify these in HTML markup as well, though, I'd use attributes instead. You can create attributes with any names you want, although to be careful I'd use names like data-xyz (e.g., use a data- prefix) as that's the HTML5 standard way of using your own attributes. Then you use getAttribute to get the value and setAttribute to set/update the value.

Categories

Resources