Cansada de ser feliz

Bienvenidos a mi flujo de conciencia

JavaScript: Tips & Tricks

| Comments

Attribute value selector with OR operator

1
2
3
4
var selected_airlines = ["UN", "SU"]
$('#journeys').find('.js-flight-airline').filter('[data-code="'+ selected_airlines.join('"],[data-code="') +'"]')

// makes the following string for the filter: '[data-code="UN"],[data-code="SU"]'

Sort HTML elements by attribute value

Get an array of checked checkboxes

1
2
3
<input type="checkbox" value="UN" name="airlines" checked>
<input type="checkbox" value="IB" name="airlines">
<input type="checkbox" value="SU" name="airlines" checked>
1
2
3
4
5
$('#airlines input:checked').map(function(){
    return $(this).val();
}).get();

// result: ["UN", "SU"]

Filter by hidden elements (with style=“display: none;”)

1
2
3
$('.js-flights').filter(function() {
    return $(this).css("display") == "none"
})

Scroll div to bottom

1
2
3
4
5
// without animation
$('#my_div').scrollTop($('#my_div').height());

// with animation 
$("#my_div").animate({scrollTop:$("#my_div")[0].scrollHeight}, 1500);

Live events

1
2
3
4
5
6
7
// click
$('.js-element').click(function (e) {
});

// live click 
$(document).on('click', '.js-element', function (e) {
});

Readonly

1
2
3
4
// make an input readonly
$('#fieldName').prop('readonly', true);
// make readonly a select field
$('#selectField').attr('disabled', true);

Select an option

1
$('#id_gender').val(gender);

Refresh a page

1
location.reload();

Scroll to element

http://stackoverflow.com/questions/6677035/jquery-scroll-to-element

1
2
3
4
5
$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

Trigger :hover with js

1
$("#link").trigger("mouseover");

Comments