Scroll a textarea to a given position with jQuery
Browsers make this very hard. Even when you explicitely set the selection inside the textarea (e. g. using jquery-fieldselection) the browser will not scroll the textarea to this selection.
What you can do instead is abuse browsers' behavior that they scroll to the end of a textarea when it gets focus. So we set the textarea's value to the text before the position, then focus it, then reset it to its original value:
function scrollTextareaToPosition($textarea, position) {
var text...
jQuery: How to replace DOM nodes with their contents
You know that you can use jQuery's text()
to get an element's contents without any tags.
If you want to remove only some tags, but keep others, use contents()
and unwrap()
. Here is how.
Consider the following example element.
$container = $('<div><strong>Hello</strong> <em>World</em></div>')
Let's say we want to discard any <em>
tags, but keep their contents.
Simply find
them, then dive into their child nodes via contents
, and use unwrap
replace their ...
Compare two jQuery objects for equality
Every time you call $(...)
jQuery will create a new object. Because of this, comparing two jQuery collections with ==
will never return true, even when they are wrapping the same native DOM elements:
$('body') == $('body') // false
In order to test if two jQuery objects refer to the same native DOM elements, use is
:
var $a = $('body');
var $b = $('body');
$a.is($b); // true
Jasmine equality matcher for jQuery
See [here](/makandra/34925-jasmine-testing-complex-types-for-e...
jQuery: How to attach an event handler only once
With "attaching an event handler once" you possibly mean one of these two things:
Register a function for an event, and discard it once that event has happened
Use one
instead of on
.
$(element).one('eventName', function() { ... });
It has the same API has on
.
When code is run multiple times that registers a function for an event, do that only once
With jQuery, you can de-register callbacks. You can use that to achieve registering a function only once.
function myAction() { ... }; // defined somewhere globally o...
Make jQuery.animate run smoother with almost no code changes
jQuery comes with .animate()
that lets you transition some CSS selectors:
function floatIn($element) {
$element.css({ 'opacity': 0, 'margin-top': 200px });
$element.animate({ 'opacity': 1, 'margin-top': 0 }, { duration: 500 });
}
The animation is implemented using setInterval
and Javascript. This works great, but it's not as smooth as a CSS transition.
Fortunately the animate
API can be mapped almo...
Unobtrusive jQuery to toggle visibility with selects and checkboxes
Use this if you want to show or hide part of a form if certain options are selected or boxes are checked.
The triggering input gets an data-selects-visibility
attribute with a selector for the elements to show or hide, like
<%= form.select :advancedness, [['basic', 'basic'], ['advanced', 'advanced'], ['very advanced', 'very_advanced]], {}, :"data-selects-visibility" => ".sub_form" %>
The elements that are shown/hidden look like
<div class="sub_form" data-show-for="basic">
only shown for advancedness = basic
</div>
...
jQuery Core 3.0 Upgrade Guide | jQuery
Since jQuery 3 saw it's first release candidate today, the links has a list of (breaking) changes.
Scroll a textarea to a given line with jQuery
You can use this code:
function scrollToLine($textarea, lineNumber) {
var lineHeight = parseInt($textarea.css('line-height'));
$textarea.scrollTop(lineNumber * lineHeight);
}
Some caveats about this code:
- Your textarea needs to have a line-height in Pixels.
- The code will scroll to the line number in the text area, not the line number of the original text. These will differ if any lines wrap at the edge of the textarea.
Also see our solution for [scrolling a textarea to a given position with jQuery](htt...
The Difference Between jQuery’s .bind(), .live(), and .delegate()
The difference between .bind(), .live(), and .delegate() is not always apparent. Having a clear understanding of all the differences, though, will help us write more concise code and prevent bugs from popping up in our interactive applications.
Vadikom » Poshy Tip - jQuery Plugin for Stylish Tooltips
With this plugin, you can create a scalable tooltip by just using a single background image for the tooltip body.
Cucumber step to manually trigger javascript events in Selenium scenarios (using jQuery)
When you cannot make Selenium trigger events you rely on (e.g. a "change" event when filling in a form field), trigger it yourself using this step:
When /^I manually trigger a (".*?") event on (".*?")$/ do |event, selector|
page.execute_script("jQuery(#{selector}).trigger(#{event})")
end
Note that this only triggers events that were registered through jQuery. Events registered through CSS or the native Javascript registry will not trigger.
Rails 3: Make "link_to :remote => true" replace HTML elements with jQuery
In Rails 2, you could use link_to_remote ... :update => 'id'
to automatically replace the content of $('#id')
.
To do the same in Rails 3, include usual rails-ujs JavaScript, and put this into your application.js
:
$(function() {
$('[data-remote][data-replace]')
.data('type', 'html')
.live('ajax:success', function(event, data) {
var $this = $(this);
$($this.data('replace')).html(data);
$this.trigger('ajax:replaced');...
SudoSlider: a jQuery slider
SudoSlider is a simple yet powerful content slider that makes no (or very few) assumptions about your markup and is very customizable.
You can basically embed any HTML into the slides, so you can mix images, videos, texts, and other stuff.
Check out the demos.
Please note:
- There is a ton to configure. Check the demos and read the docs.
- It does not bring styles for prev/next links etc, so you need to style controls yourself (which I consider to b...
Autofocus a form field with HTML5 or jQuery
In Webkit you can use the HTML5-attribute autofocus
:
= form.text_field :title, :autofocus => 'autofocus'
Here is a jQuery fallback for browsers that don't speak HTML5:
var Autofocus = {
supported: function() {
return 'autofocus' in document.createElement('input');
},
fake: function() {
$('[autofocus]').focus();
},
extend: function() {
Autofocus.supported() || Autofocus.fake();
}
};
$(Autofocus.extend);
jQuery: Find a selector in both descendants and the element itself
jQuery's find
looks in the element's descendants. It will never return the current element itself, even if the element matches the given selector.
Require the attached file and you can now say:
$('.container').findWithSelf('.selector')
This is sort of like closest
, but it looks in descendants instead of ancestors.
Soft-scroll to an anchor with jQuery
This snippet makes links that refer to an anchor (like "<a href="#something">...</a>
") scroll softly to it.\
In this example we only do it for links that also own a data-animate
attribute.
$('a[href^="#"][data-animate]').live('click', function() {
var hash = $(this).attr('href');
var offset = $(hash).offset();
if (offset) {
$('html, body').animate({ scrollTop: offset.top }, 'slow');
location.hash = hash;
return false;
}
});
Note that this could basically work for any element whos...
Chosen - makes select boxes better
Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors.
OscarGodson/jKey - GitHub
jQuery plugin to register callback functions to keyboard shortkuts. Keyboard events in vanilla Javascripts are super-painful to work with, so hopefully this library can help.
flot - Google Code
Flot is a pure Javascript plotting library for jQuery. It produces graphical plots of arbitrary datasets on-the-fly client-side.
Underscore.js
Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux.
Apprise - The attractive alert alternative for jQuery
An alert alternative for jQuery that looks good. Apprise is a very simple, fast, attractive, and unobtrusive way to communicate with your users. Also, this gives you complete control over style, content, position, and functionality. Apprise is, more or less, for the developer who wants an attractive alert or dialog box without having to download a massive UI framework.
Fix multiple CKEditor instances using jQuery adapter - fixed since 4.2
Using the jQuery adapter breaks the built-in save function of CKEditor.
Phenomenon: The page is submitted correctly, but the original values of the form fields were posted instead of what was typed in the editors.
Work around: Basicly instead of initiating the editor using the above example I ended up using the following:
$( 'textarea.editor').each( function() {
CKEDITOR.replace( $(this).attr('id') );
});
Note: This assumes that each field using the editor has its own unique ID.
Howto set jQuery colorbox overlay opacity
Setting the colorbox opacity by hash parameter when initializing doesn't work the way like the documentation tells you.
$(selector).colorbox({ ..., opacity: 0.5, ... }); // has no effect
The opacity value of 0.5
will be overwritten by the inline style attribute style="opacity: 0.9"
that colorbox sets.
To manually set the opacity you have to add the following css rule
#cboxOverlay { opacity: 0.5 !important; }
Problems with Rails 3 Remote Links and Forms Using jQuery .live() in IE
There is a problem with AJAX response handling for Rails 3 remote links and forms in Internet Explorer. This problem affects applications still using jQuery 1.4.2.