I have a custom built ajax [div] based dynamic dropdown.
I have an [input] box which; onkeyup, runs an Ajax search which returns results in divs and are drawn back in using innerHTML. These divs all have highlights onmouseover so, a typical successful search yields the following structure (pardon the semi-code):
[input]
[div id=results] //this gets overwritten contantly by my AJAX function
[div id=result1 onmouseover=highlight onclick=input.value=result1]
[div id=result2 onmouseover=highlight onclick=input.value=result2]
[div id=result2 onmouseover=highlight onclick=input.value=result2]
[/div]
It works.
However, I'm missing the important functions behind regular HTML elements. I can't keyboard down or up between "options".
I know javascript handles keyboard events but; I haven't been able to find a good guide. (Of course, the follow-up question will end up being: can I use <ENTER> to trigger that onclick event?)
What you need to do is attach event listeners to the div with id="results". You can do this by adding onkeyup, onkeydown, etc. attributes to the div when you create it or you can attach these using JavaScript.
My recommendation would be that you use an AJAX library like YUI, jQuery, Prototype, etc. for two reasons:
It sounds like you are trying to create an Auto Complete control which is something most AJAX libaries should provide. If you can use an existing component you'll save yourself a lot of time.
Even if you don't want to use the control provided by a library, all libraries provide event libraries that help to hide the differences between the event APIs provided by different browsers.
Forget addEvent, use Yahoo!’s Event Utility provides a good summary of what an event library should provide for you. I'm pretty sure that the event libraries provided by jQuery, Prototype, et. al. provide similar features.
If that article goes over your head have a look at this documentation first and then re-read the original article (I found the article made much more sense after I'd used the event library).
A couple of other things:
Using JavaScript gives you much more control than writing onkeyup etc. attributes into your HTML. Unless you want to do something really simple I would use JavaScript.
If you write your own code to handle keyboard events a good key code reference is really handy.
Off the top of my head, I would think that you'd need to maintain some form of a data structure in the JavaScript that reflects the items in the current dropdown list. You'd also need a reference to the currently active/selected item.
Each time keyup or keydown is fired, update the reference to the active/selected item in the data structure. To provide highlighting information on the UI, add or remove a class name that is styled via CSS based on if the item is active/selected or not.
Also, this isn't a biggy, but innerHTML is not really standard (look into createTextNode(), createElement(), and appendChild() for standard ways of creating data). You may also want to see about attaching event handlers in the JavaScript rather than doing so in an HTML attribute.
Related
So, I am trying to find the part of the JS where a certain element is being changed. I have looked around and I can't find a way to see how those events are handled.
The scenario is: there is a hidden field with a certain value. When I submit the form, the value changes right before being submitted.
What i am looking for is the method that changes that value.
Any advice on how to approach this would be very helpful as I am not very good when it comes to JS. Oh, and it looks like the code is obfuscated so most of the function names are one letter .
The approach I use in these situations is to examine the HTML around the area that is being modified, note all possible ways that code could find the appropriate DOM elements (form names, id values, class names, etc...) and then look through the code to find where it might be querying the DOM to find the DOM element that is being changed using one of these identifiers. Since the identifiers can't be obscured, they should be in the code in normal English the same as they appear in the HTML.
In addition, you can make a list of all event listeners that are being set in the code and pay particular attention to event listeners on any objects near the one being changed. Since it's a form submission, you can look for the submit event or click event on a form submission button.
When you see event handlers that you aren't sure whether they are involved, you can simply set a breakpoint in them and see if their code is hit during the action you are investigating. I often find it helpful to make my own copy of the code in my own editor and start adding code comments to it as I find out what something does or how it works. This gives me more of a running knowledge base rather than having to just remember everything. This is even more useful when the variable names have all been obscured.
this is more a strategic question than a specific one, but I think it's precisely asked so here goes:
let's say I have a page or ap that has 3 separate sections. A change on part of the form sends an ajax post to the server, and this requires a change in section two. I want to send back the re-processed HTML output of section 2, and have this replace the original state of section 2
but, section 2 has many elements that have change, click, drag etc. bindings - and from experience when I do a html replace, I lose all my bindings.
HOWEVER, this leaves me with rewriting certain things in many of the elements in section 2 individually so as not to lose the bindings.
I KNOW there's an easier approach to this, seems like a common problem. Can anyone provide me with the "aha" part of this question, and perhaps a few examples or links? I really appreciate it.
You will need to divide the problem into two sections
Handling events
This can be done using event delegation using $.on(). ie instead of registering events on the element you register on a parent which will not be removed
Ex:
$('.container').on('click', 'a', function(){
//do something
})
Handling widgets like draggable
Here I think you are out of luck because I don't see any other way than to reinitialize those widgets once the new dom elements are added
Ex:
var ct = $('.container').html('');
ct.find('li').draggable({})
You could use Event Delegation, so you don't have to re-bind.
From this ticket
In case anyone arrives here as I did looking for a quick alternative to replaceWith() that keeps attached events, it can be done using a combination of existing functions in the current API:
this:
old.replaceWith( new );
can be changed to:
old.before( new ).detach();
Both return a handle to the removed element, so depending on the use case it should be pretty simple to change.
I was wondering if there is any way to find all the scripts associated with a particular element in web page.
That is if there is a photo, and there is two attached jquery function like on mouse over and on click, I need to get details of this functions without looking onto entire script.
One way is with a bookmarklet called Visual Event
There isn't really an easy way. I spent a few days trying to write an augmentation wrapper/extension that would track all even assignment in page and thus allow for inspection of such - the problem is that it requires tweaking for each library, and iirc wasn't useful if any native event assignment was used.
This is exactly the reason there needs to be well organized code, and remembering that "unobtrusive" doesn't mean "incomprehensible" - try to keep all your event assignments well organized and easily associated/found for a particular element.
I have a grid and there is a column which contains <a> anchor tag with some additional information in <data-..> tag and has a class name <class='myspeciallink'>. And in my unobtrusive JS script I select all the elements with that class name and apply live('click'). I need that to be live() because the grid gets generated in the runtime.
What happens inside the live('click') handler? I use that additional data and add a <div> to the page based on that data. Which in its turn used to generate jQuery UI dialog. It works great on my computer.
But! How could that work in real-world? Should I be bothered about possible performance implications? I feel that applying live() on more than a dozen elements instantaneously
would affect the performance. Especially with rather complicated handler like mine - it needs to get the data, parse the data, create a div, apply a dialog and etc.
Does that smell like a bad design? Could you suggest a different approach or my concerns are unfounded? Can I use some sort of a profiler tool to find the bottlenecks in my javascript?
UPD: Still nobody suggested any profiling tool. firebug and chrome dev tools are good, but maybe there is something even better?
live("click") is actually better up-front from a performance standpoint: Instead of binding an event handler to each matched element, you're applying a single event handler which waits for events to bubble up and then sees if the element that triggered the event matches the selector .live was called on.
Compare this to $('selector').click(...) which does loop over each element and bind a new event handler. live('click') has no additional overhead regardless of how many page elements match its selector. Depending on how many elements your selector matches, using .live can avoid a delay of up to a few seconds during the initial load of each page.
However, the event handler must check each event which bubbles up against its selector, to see if there is a match. This is going to add a small amount of overhead to every click event, but chances are very good that your users will not notice the difference.
Peter bailey also has a nice post about this: Performance difference between jQuery's .live('click', fn) and .click(fn)
I have got a table, and it has a label in one of its containers, what I want is so when the user clicks on that label it will turn into a optionbox with options and the user can select one then when he clicks out it will switch to the label he chose.
I am assuming this can be done in Javascript.
Something like this? It's just a quick-and-dirty JavaScript implementation, so if you have other, specific requirements, feel free to add to the question.
Yes, you can do this in JavaScript.
Here is a small, self-contained example that shows the answer using the javascript framework jQuery. If you are going to be heavily into Javascript on your page, I recommend using a framework.
Here is that same example using no Javascript frameworks.
Both examples rely on providing a class to a div containing the label/select indicating whether it is currently a label or a select. Both use a click handler on the whole document and a click handler on the label/select.
I highly recommend you digging into events and handlers in Javascript as well as the Document Object Model (DOM) if you already haven't to understand how this works.