The page moves back up to the top when you click any of the buttons under the second "Clients" heading here: http://kodiakgroup.com/clients.php
I have tried the preventDefault function as well as return false per suggestion here in the on change functions you can see below. See what I can do to prevent this behavior?
Part I changed:
//Toggle select all/deselect function
$('#vertical-filters input').change(function (e) {
$('.selectAllBoxes').prop('checked', false);
getCustomers();
e.preventDefault();
return false;
});
$('.selectAllBoxes').change(function (e) {
$('#vertical-filters input').prop('checked', false);
getCustomers();
e.preventDefault();
return false;
});
All of the javascript:
$(function () {
$('.selectAllBoxes').prop('checked', true);//Set checkboxes as checked by default
getCustomers(); //Initially call all customers
function getCustomers()
{
$('ul#customers').html('');//empty list
var definedCategoryArray=new Array();
var categoriesPlural= new Array();
var customerSplit=new Array();
for(var x=0; x< $('#vertical-filters input').length; x++){
var thisItem=$('#vertical-filters input')[x];
var thisItemName=$(thisItem).attr('id');
if($('.selectAllBoxes').is(':checked')){
definedCategoryArray[thisItemName]=true;
}
else{
if ($(thisItem).is(':checked'))
definedCategoryArray[thisItemName]=true;
else
definedCategoryArray[thisItemName]=false;
}
}
$.getJSON('customers.json', function(data) {
for(var index in definedCategoryArray){ //cycle through categories array
for(var i=0; i<data.customers.length; i++){ //cycle through json data
if (definedCategoryArray[index]==true){//if the value in the array is true (item checked)
//console.log(data.customers[i].customerName+ ' : ' + data.customers[i].category);
if(data.customers[i].category.indexOf(',') != -1) //if there is more than one category, detect the comma seperating them
categoriesPlural = data.customers[i].category.split(',');
else //there is only one category
categoriesPlural[0]=data.customers[i].category;
for (var y = 0; y<categoriesPlural.length; y++){
//console.log(categoriesPlural[y]);
if(categoriesPlural[y] == index){ //match category (from definedCategoryArray index) to items in json object to parse
$('ul#customers').append('<li class="' +data.customers[i].customerName.replace(/\s+/g, '-') + '" id="'+data.customers[i].customerName.replace(/\s+/g, '-')+'"><img src="'+ data.customers[i].imageLink +'" alt="'+ data.customers[i].customerName +'" /></li>');
checkDuplicates(data.customers[i].customerName.replace(/\s+/g, '-'));
}
}
}
}
}
}).fail(function() { console.log( "error" ); });
}
function checkDuplicates(customerName){
for(var x=0; x< $('#customers li').length; x++){//loop through clients already on the page to prevent duplicates
var thisClient=$('#customers li')[x];
var thisClientName=$(thisClient).attr('id');
if(thisClientName == customerName){
var superClient1=$('.'+customerName)[1];
var superClient2=$('.'+customerName)[2];
if (superClient1)
$(superClient1).css('display','none');
if(superClient2)
$(superClient2).css('display','none');
//console.log(customerName + '=' + thisClientName + ' emptied');
}
}
}
//Toggle select all/deselect function
$('#vertical-filters input').change(function (e) {
$('.selectAllBoxes').prop('checked', false);
getCustomers();
e.preventDefault();
return false;
});
$('.selectAllBoxes').change(function (e) {
$('#vertical-filters input').prop('checked', false);
getCustomers();
e.preventDefault();
return false;
});
});
It's not actually going back to top, but you are removing items. The page is shrinking and scroll disapear then you add item and the page expand without scrolling back.
An easy hack to do is to fix the heigh of the ul before removing items and then remove the attribute style. Like that :
$('#vertical-filters input').change(function (e) {
$('.selectAllBoxes').prop('checked', false);
$('ul#customers').height($('ul#customers').height()); //fix the height
getCustomers();
$('ul#customers').removeAttr('style'); //Reset the height
});
Repeat for all the .change() functions.
It is not tested but in theory, it should work
That's because you are removing the content from the ul#customers container, check this line in your HTML
function getCustomers()
{
$('ul#customers').html('');//empty list
...
}
There are some workarounds to avoid this scroll, you can check this post
As another answer here suggests, try setting a height on the ul. This would be my approach:
function getCustomers() {
var $customers = $('ul#customers');
$customers.css('height', $customers.height());
$customers.html(''); //empty list
// the rest of your getCustomers() function
// at the very end, remove the height
$customers.css('height', '');
}
So, you start with explicitly setting a height on the ul. This will keep it from collapsing. Then, you can empty it and add in the new content. At the very end, you remove the height, and the ul will collapse to whatever height its contents require.
This will probably still be a little jolting. You could consider animating the height either with jQuery $.animate() or CSS3 animations
Thanks guys! Both were good answers so I wasn't sure which one to mark. I actually just set a min-height on the container and it fixed it! :)
Related
I'm using this awesome bouncy filter from Codyhouse but i can't for the life of me figure out how to make it run automatically i.e flip on its own and still accept user click events. The jsfiddle...Thanks.
jQuery(document).ready(function($) {
//wrap each one of your filter in a .cd-gallery-container
bouncy_filter($('.cd-gallery-container'));
function bouncy_filter($container) {
$container.each(function() {
var $this = $(this);
var filter_list_container = $this.children('.cd-filter'),
filter_values = filter_list_container.find('li:not(.placeholder) a'),
filter_list_placeholder = filter_list_container.find('.placeholder a'),
filter_list_placeholder_text = filter_list_placeholder.text(),
filter_list_placeholder_default_value = 'Select',
gallery_item_wrapper = $this.children('.cd-gallery').find('.cd-item-wrapper');
//store gallery items
var gallery_elements = {};
filter_values.each(function() {
var filter_type = $(this).data('type');
gallery_elements[filter_type] = gallery_item_wrapper.find('li[data-type="' + filter_type + '"]');
});
//detect click event
filter_list_container.on('click', function(event) {
event.preventDefault();
//detect which filter item was selected
var selected_filter = $(event.target).data('type');
//check if user has clicked the placeholder item (for mobile version)
if ($(event.target).is(filter_list_placeholder) || $(event.target).is(filter_list_container)) {
(filter_list_placeholder_default_value == filter_list_placeholder.text()) ? filter_list_placeholder.text(filter_list_placeholder_text): filter_list_placeholder.text(filter_list_placeholder_default_value);
filter_list_container.toggleClass('is-open');
//check if user has clicked a filter already selected
} else if (filter_list_placeholder.data('type') == selected_filter) {
filter_list_placeholder.text($(event.target).text());
filter_list_container.removeClass('is-open');
} else {
//close the dropdown (mobile version) and change placeholder text/data-type value
filter_list_container.removeClass('is-open');
filter_list_placeholder.text($(event.target).text()).data('type', selected_filter);
filter_list_placeholder_text = $(event.target).text();
//add class selected to the selected filter item
filter_values.removeClass('selected');
$(event.target).addClass('selected');
//give higher z-index to the gallery items selected by the filter
show_selected_items(gallery_elements[selected_filter]);
//rotate each item-wrapper of the gallery
//at the end of the animation hide the not-selected items in the gallery amd rotate back the item-wrappers
// fallback added for IE9
var is_explorer_9 = navigator.userAgent.indexOf('MSIE 9') > -1;
if (is_explorer_9) {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
} else {
gallery_item_wrapper.addClass('is-switched').eq(0).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
});
}
}
});
});
}
});
function show_selected_items(selected_elements) {
selected_elements.addClass('is-selected');
}
function hide_not_selected_items(gallery_containers, filter) {
$.each(gallery_containers, function(key, value) {
if (key != filter) {
$(this).removeClass('is-visible is-selected').addClass('is-hidden');
} else {
$(this).addClass('is-visible').removeClass('is-hidden is-selected');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm assuming by "make it run automatically" you're talking about triggering the content-selection animation programatically, rather than requiring a user click. One possible solution is to assign an id to the selection elements, and then register the click handler directly to those elements, rather than the parent filter_list_container. Then, you can use jQuery's trigger() method to simulate a click on the appropriate element.
Assign an id in the html like this:
<a id="green" href="#0">Green</a>
Then register the click handler like this:
$("#red, #green, #blue").on('click', function(event){ ... }
...and trigger like this:
$("#green").trigger("click");
Here's a JSfiddle with an example.
I have a simple jq code to create autosuggestions (google like). It works fine and I just want to add keyboard events handlers. However I have some problems with it. When I want to choose the next suggestion with event 40 (arrow down) it get all the suggestions instead of just the next one. Any idea how to fix it?
$(document).ready(function(){
var people = ['Peter Bishop', 'Nicholas Brody', 'Gregory House', 'Hank Lawson', 'Tyrion Lannister', 'Nucky Thompson'];
var cache = {};
var drew = false;
$("#search").on("keyup", function(event){
var query = $("#search").val()
if($("#search").val().length){
//Check if we've searched for this term before
if(query in cache){
results = cache[query];
}
else{
//Case insensitive search for our people array
var results = $.grep(people, function(item){
return item.search(RegExp(query, "i")) != -1;
});
//Add results to cache
cache[query] = results;
}
//First search
if(drew == false){
//Create list for results
$("#search").after('<div id="res"></div>');
//Prevent redrawing/binding of list
drew = true;
//Bind click event to list elements in results
$("#res").on("click", "div", function(){
$("#search").val($(this).text());
$("#res").empty();
});
$("#search" ).keydown(function( event ) {
if ( event.which == 40 ) {
$("#search").val($(".suggestions").next().text());
}
});
}
//Clear old results
else{
$("#res").empty();
}
//Add results to the list
for(term in results){
$("#res").append("<div class = 'sugestions'>" + results[term] + "</div>");
}
}
//Handle backspace/delete so results don't remain
else if(drew){
$("#res").empty();
}
});
});
<input id="search" type="text">
You need to keep track of the currently selected suggestion. Simplest approach is probably to add/remove a className, something like this :
if(drew == false){
//Prevent redrawing/binding of list
drew = true;
//Create list for results, and bind click event to list elements in results
var $res = $('<div id="res"></div>').insertAfter("#search")
.on("click", "div", function() {
$(".suggestions").removeClass('selected');
$("#search").val($(this).addClass('selected').text());
$("#res").empty();
});
var $search = $("#search").keydown(function(event) {
var $suggestions, $selected, index;
if (event.which == 40) {
$suggestions = $(".suggestions");
$selected = $suggestions.find('.selected').eq(0);//.eq(0) shouldn't be necessary, but just in case ...
if($selected.length) {
index = ($selected.index() + 1) % $suggestions.length;//assuming the suggestions are siblings
} else {
index = 0;
}
$(".suggestions").removeClass('selected');
$search.val($(".selected").eq(index).addClass('selected').text());
}
});
} else { //Clear old results
$("#res").empty();
}
Not sure if that's 100% correct as I've had to make a couple of assumptions, but the approach should be about right.
I spent several hours on this and couldn't find a solution that worked, so I'm turning to you :) As you can see from this fiddle (http://jsfiddle.net/PPcgE/), I was able to target the radio buttons by click with this code:
$("input[type='radio']").click(function (e) {
if ($('.cos-cond').is(":visible")) {
e.preventDefault();
} else {
var clicked = $(this).attr('title');
var cls = [$('.one'), $('.two'), $('.three'), $('.four'), $('.five'), $('.six'), $('.seven'), $('.eight'), $('.nine'), $('.ten')];
for (i = 0; i < cls.length; i++) {
if (cls[i].attr('title') === clicked) {
cls[i].fadeIn('fast', function(){
setTimeout(function(){
$('.cos-cond').fadeOut('slow');}, 5000);
});
}
}
}
});
I'm trying to do exactly the same thing (displaying either span.eleven, span.twelve or span.thirteen this time) based on which option is clicked/selected in the select box. The best I've been able to manage is to get all three to appear at once.
Your original code is broken, i've create a fiddle that fixes it.
Your problem was when you were fading out, your selector was selecting all of them, visible or not, and then showing ALL of them while fading out.. thus always showing the last one (topmost).
if (cls[i].attr('title') === clicked) {
cls[i].fadeIn('fast', function(){
setTimeout(function(){
$('.cos-cond:visible').fadeOut('slow');}, 5000);
});
}
Beyond that you need to provide your attempt at how you tried to get the dropdown box working. You only provided the old code and nothing more.
Your code shouldn't be longer than this
$(document).ready(function(){
$("input[type='radio']").click(function (e) {
$('.cos-cond, .work-cond').hide();
var clicked = $(this).attr('title');
$('span.cos-cond[title=' + clicked + ']').fadeIn(300);
});
$("select").change(function (e) {
$('.cos-cond, .work-cond').hide();
var value = $(this).val();
var title = $('option[value="' + value + '"]', this).attr('title');
$('span.work-cond.' + title).fadeIn(300);
});
});
http://jsfiddle.net/PPcgE/5/
Try
$(".emf-hide").change(function(e){
var val = $(".emf-hide option:selected").val();
$('.work-cond').hide();
switch(val){
case 'Like New - No Functional Problems':
$('.eleven').show();
break;
case 'Minor Functional Problems':
$('.twelve').show();
break;
case 'Non-functional':
$('.thirteen').show();
break;
}
});
Working example here
On my webpage, I have a table in which there's a radio button for each row. The name of radio buttons is the same for all rows to access them as a group. I have a button which alerts the row number whose radio button is checked. I'd like to access individual elements of the table of that row as well. Any thoughts as top how I might be able to achieve this would be very welcome.
Here's a Fiddle for the issue:
http://jsfiddle.net/Gz668/13/
On the click of the button "edireq", it currently alerts the row number whose radio button is checked. I'd like to access the values of other fields of the table (requestor, approver, status etc. too.)
Here's the jquery code
$("#edireq")
.button()
.click(function () {
var ele = document.getElementsByName('reqradio');
var len = ele.length;
var flag = -1;
for (var j = 0; j < len; j++) {
if (ele[j].checked) {
flag = j;
}
}
if (flag > -1) {
alert("Row : " + (flag + 1));
} else {
alert("Select a row first");
}
});
Thanks.
You have an odd mix of native javascript and jQuery. You can use the :checked selector to get the chosen radio button, then get the closest tr and read the text of each td within that row. Try this:
$(document).ready(function () {
$('#reqtablenew tr').click(function () {
$('#reqtablenew tr').removeClass("active");
$(this).addClass("active").find('input[name="reqradio"]').prop('checked', true);
});
$("#edireq").button().click(function () {
var $ele = $('input[name="reqradio"]:checked');
if ($ele.length) {
var $tds = $ele.closest('tr').find('td');
var id = $tds.eq(1).text();
var requestor = $tds.eq(2).text();
// and so on..
alert(id);
alert(requestor);
}
else {
alert("Select a row first");
}
});
});
Example fiddle
Try this:
var list = ["Req id","Requestor","Approver","Status","Product","Version","Source","Destination"]; //list of title
if (flag > -1) {
$(".active").find("td:gt(0)").each(function(i){
console.log(list[i]+": "+$(this).text());
});
}
Fiddle here.
I came up with the following:
http://jsfiddle.net/Gz668/16/
$(document).ready(function () {
$("table").on("click", "tr", function(){
$(".active").removeClass("active");
$(this).toggleClass("active");
$(this).find("input[type='radio']").prop("checked", true);
});
$("#edireq").on("click", function(){
activeRow=$(".active");
cells=activeRow.children();
if(cells.length >0){
row={
select:cells[0],
requestId:cells[1],
requestor:cells[2],
approver:cells[3],
status:cells[4],
product:cells[5],
version:cells[5],
source:cells[6],
destination:cells[7]
};
alert(row.requestor.textContent);
}
})
});
How do I determine the state of a checkbox (i.e. checked or unchecked) with the following code:
function deleteItems() {
var items = $('.td_checkbox');
for (var item in items) {
// this doesn't work
if ($(item).is(:checked) == true)
alert('delete my div if checked!');
}
}
You are missing the quotes " around :checked: .is(":checked").
But doing it the jQuery way:
function deleteItems() {
$('.td_checkbox:checked').remove(); // or .parent().remove();
}
You need quotes around :checked, but I also don't think your loop works correctly.
This will do what you want (use each() rather than for item in items)
function deleteItems() {
$('.td_checkbox').each(function(){
if ($(this).is(":checked"))
alert('delete my div if checked!');
});
}
You can use the attr property to check and/or set an attribute
function deleteItems() {
var items = $('.td_checkbox');
for (var item in items) {
// this doesn't work
if ($(item).attr('checked') == true)
$(item).remove();
}
}
Or you can also filter the checked ones before hand
function deleteItems() {
var items = $('.td_checkbox:checked');
for (var item in items) {
$(item).remove();
}
Skip jQuery for the checkedness check and just use the checkbox element's couldn't-be-simpler-works-in-every-browser-released-since-1995 checked property:
function deleteItems() {
$('.td_checkbox').each(function() {
if (this.checked) {
alert('delete my div if checked!');
}
});
}