I'm currently working on a web application using HTML 5, CSS and JQuery. I have an unordered list (ul) for displaying page links, with each li element containing the page link. This list is created dynamically using jQuery.
What I would like to do is to have the list elements display only the page name in the link, but at the same time retain the full link path. For example, "http://www.foo.com/xyz/contactus" would be displayed as "contactus", but the li element would still "know" the full link path. For this purpose the value attribute of li would have been perfect, since i could set them like this:
var ul = $('<ul/>').attr('id', 'linkList');
for (var i = 0; i < linksOnPage.length; i++) // linksOnPage is an array with all the links
{
var pgName = linksOnPage[i].toString().slice(steps[i].toString().lastIndexOf('/') + 1);
// Create list element and append content
var li = $('<li/>').text(pgName); // Set the text to the page name
li.attr('value', linksOnPage[i].toString()); // Set the value to the full link
ul.append(li);
}
This would create a list like:
<ul>
<li value="http://www.foo.com/xyz/contactus">contactus</li>
...
</ul>
Unfortunately the value attribute of li has been deprecated since HTML 4.01 (anyone know the rationale behind this? Seems pretty useful to me...).
So, I would like some advice on how to proceed. One option is to ignore the deprecation and use the value attribute anyway, since all the major browsers still support it, but I'm not very keen on using a deprecated feature and it just feels wrong.
Any ideas?
Change from:
<li value="http://www.foo.com/xyz/contactus">contactus</li>
To:
<li data-value="http://www.foo.com/xyz/contactus">contactus</li>
data-* pattern is the new HTML5 way of keeping values in DOM elements.
You can get the values in one of the two ways:
$('#li-Id').data('value');
$('#li-Id').attr('data-value');
You can read this blog post of John Resig on those attributes.
jQuery data function
Simply use a data attribute (intro; longer tutorial; spec):
<li data-path="http://www.foo.com/xyz/contactus">contactus</li>
As a plus, jQuery conveniently detects and exposes the values of such attributes through the .data method.
Even though value was deprecated, it could still be used and accessed w/JavaScript. You're only giving up validation status!
Alternatively you could either use data-* attributes (as I see others have suggested) or map values directly to DOM elements - since you're generating this markup at runtime you could just add a property like so (JS allowing you to do this is both a blessing and a curse):
li.someLinkPath = 'some url here';
//and in the click handler you could access this as
this.someLinkPath;
Still... if you're intending to use this for navigation, why not just use an anchor with an href?
Related
So I'm using this code to:
$('.something').on('click', function () {
console.log($(this).data('id'));
}
And for some reason, if I modify the data-id using the inspector, jQuery still sees the id that was there in the beginning. However, I tried the same thing using JS and it does see the changes. This makes me wondering if jQuery caches in some way the elements selected and uses them instead of the actual DOM.
Can someone please explain what happens and how jQuery does the event binding in the background?
Later edit: I want to specify that I'm talking about the "data-" attribute that I put in the HTML, not about the '.data()' provided by jQuery. Not sure if it's the same thing.
jQuery caches elements selected?
No. But the data managed by data is stored in an object cache maintained by jQuery, keyed by a unique identifier jQuery adds to the element (so it can look up the data). data is only initialized from data-* attributes, it is not an accessor for them. It's both more and less than that.
If you're interested, you can see that as an "expando" property on the element instance, it'll start with "jquery" and have a long number attached to it (currently; it's undocumented — for good reason — so this may change):
var foo = $("#foo");
console.log(foo.data("info")); // hi there
console.log("Expando name: " + Object.getOwnPropertyNames(foo[0]).find(name => name.startsWith("jQuery")));
<div id="foo" data-info="hi there"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Due to a limitation of the Javascript library I'm using, I can't assign an id to a <div>. Unfortunately, I don't know how to attach a Tooltip object from Tipped, a Javascript tooltip library, to the element without an id. I don't know if this is possible, but I'm trying to find the object via other means which will hopefully allow me to modify the id.
The element I'm looking for is a button on a toolbar, but it's not an HTML button. It's a <div> that has CSS styles and Javascript events assigned to make it look and feel like a button. I know the class name of the parent and I know the id of the grandparent <div>, but that's as much as I know. Part of the issue is that there doesn't seem to be a good reference for how to iteratively operate on HTML objects once you get a reference to them. I've seen plenty of examples like this:
var x = document.getElementsById("asdf")
but no follow-up code showing how to actually do anything. What's in x? What methods does it have? I know of innerHTML and innerTEXT, but I can't figure out if they apply to x, a child of x, or ???. The Chrome console has helped a little bit, but I'm basically lost.
This is the relevant code for my button:
As you can see, there is no id on the Export button, but the parent has a class name and the grandparent has an id. The other snag is that the grandparent's id isn't static. It always starts with "dhxtoolbar" and there is only one toolbar on the page, but I haven't been able to make a regex search find the toolbar.
Ultimately, I'd like to be able to attach a Tipped tooltip to the Export button. I think Tipped requires an id, but maybe it doesn't. Regardless, I'd like to understand more about how to iterate through the DOM and, as a bonus, figure out how or if I can change the id of an element on a live page. Thanks.
Tipped actually accepts any CSS selector as an argument. If the class is unique, you could target it that way:
Tipped.create('.dhx_toolbar_btn', 'some tooltip text');
Or if the class isn't unique, you could try target it via the tree structure. Made up example:
Tipped.create('.header .sidebar .dhx_toolbar_btn', 'some tooltip text');
I noticed in your html that the buttons have empty title attributes (or maybe your inspector just added them). If you can set the title attribute for the buttons Tipped will pick it up automatically. Example:
<div class="dhx_toolbar_btn" title="test title">
You would then only have to use:
Tipped.create('.dhx_toolbar_btn');
And Tipped will automatically pick up the title and use it.
This is what I was trying to have explained:
var Obj = document.getElementsByClassName("classname");
var ObjChildren = Obj[0].getElementsByTagName("tag")
var searchText = "string";
for (var i = 0; i < ObjChildren.length; i < i++) {
if (ObjChildren[i].innerHTML == searchText) {
console.log(ObjChildren[i].innerHTML);
}
}
I'm trying to make a simple image browser for TinyMCE which I am using in my CMS. As part of this I need to detect whether the user has selected an existing image, so I can display the "edit" form instead of the "choose an image form".
var selected_html = ed.selection.getContent();
var $elem = $(selected_html);
console.log($elem);
The first function returns the user selected text from the editor window as a string of HTML. I then would like to use jQuery (although plain javascript is just ok too) to check if this string contains an img tag before subsequently grabbing the src and title attributes for editing.
Now I've got as far as getting the html to turn into an object. But after this I can't manage to search it for the img element. After reading this (How to manipulate HTML within a jQuery variable?) I tried:
$elem.find('img');
But it just comes out as an "undefined" object...
I think I'm missing something fairly obvious here (it is getting late), but after an hour I still can't figure out how to grab the img tag from the selection. :(
Many thanks in advance.
Because the <img> is at the root of the jQuery object, you need to use .filter() instead of .find().
$elem.filter('img');
The .filter() method looks at the element(s) at the top level of the jQuery object, while .find() looks for elements nested in any of the top level elements.
If you're not sure beforehand where the target element will be, you could place the HTML into a wrapper <div> to search from. That way the HTML given will never be at the top.
var selected_html = ed.selection.getContent();
var $elem = $('<div>').html(selected_html);
var $img = $elem.find('img');
Try to see what is really inside your $elem variable. Just do a console.log($elem) using both Firefox and Firebug and you should be able to manage quite alright! ;)
I have an asp:bulletedlist control, which sits inside a div tag, and I need to count the number of list items inside the control. Searching the internet, and noting the fact the html given back by the items is a list i.e. <li>, I thought I could use an example of:
var listcontrol = document.getElementById('BulletedList1');
var countItems = listcontrol.getElementByTagName('li').length;
However, when I do this, it throws and error saying that no object exists for this control.
So, my problem is, and because I must do this clientside because I want to use this to set the height of the div tag, is how do you count the number of items inside a asp:bulletedlist control with javascript?
You can't use document.getElementById like you are using it because the actual ID for an Asp.Net control when rendered is different than what you set for the ID on the control. View the source of your page and you will see what the actual ID is. You can then use that if you want and this code should work, but it would break if you ever moved the bulletedlist control, since the hierarchy would change.
Another way to do this would be to use jQuery. In your example, you could do this:
$('[id$=BulletedList1]').children('li').size()
This would select the element that ends with 'BulletedList1', gets the li children, and then returns the size of the collection.
I use PHP and javascript via prototype.
i have a threaded comments page that on open
by default via javascript call to a PHP file data returned via JSON, only parent comments are retrieved in the db. (in short only parent comments are fetched from db and displayed)
then the parents are loaded and formatted to be shown on the page with a link to get and display its child comments, link example:
<span id="moreparent8351" onclick="insertChildDiv('parent8351')">1 Replies and more</span>
the span link above calls the javascript function "insertChildDiv()" that basically gets comments whose parent_id=parent8351, also using a PHP file that returns data via JSON to the javascript that dynamically inserts this child comments nested under its parent comment.
then the span link above using prototype transforms into:
<span id="moreparent8351" onclick="$('childparent8351').toggle()">1 Replies and more</span>
now here is the problem, this inserted content inside this div with id=childparent8351 wont respond to the hide/show toggle ONLY in IE v6,v7 and v8. other browsers work fine.
it looks like IE cannot apply the hide/show toggle to a dynamically inserted content.
I tried hardcoding the inserted content that i see in fogbugz to the page and testing it again on IE, guess what? toggle works!
I dont want to fetch all the comments both parent and child and then hide the child comments, that is a waste of resources on something that we are not sure is important or to be read by the users.
Is there a workaround? if there is none, then i hope this post will help others on their design stage for something similar.
Element.toggle() should work fine with dynamically generated content. Your problem most likely lies within the method you use to generate this content.
You stated:
then the span link above using
prototype transforms into:
<span id="moreparent8351" onclick="$('childparent8351').toggle()">1 Replies and more</span>
How exactly are you changing the onclick attribute of the span element?
First of all, I definately would not recommend changing an onclick event on-the-fly. It is probably better to use one function that checks the current state of what you are trying to do and executes the appropriate code.
Be sure not to "transform" your span element, including the onclick attribute using innerHTML. Chances are the DOM is still trying to reference a function that you have just removed. If updating your onclick attribute at all, do it like this:
var element = $('moreparent8351');
// this automatically removes previous onclick handlers set in this manner
element.onclick = function() { // do stuff };
...or, when you want to it the Prototype way:
var element = $('moreparent8351');
// OPTIONAL: remove previous handler, if set
element.stopObserving('click', my_cool_function());
// attach new handler
element.observe('click', function() { // do stuff });