I'm building a page that features a hierarchical tree-type structure. I've posted a simplified version of it at JSFiddle
It mostly works as I'd like but for one thing - on clicking closed a Brand-level row I would like, as well as the town and shoe rows to contract (which they do), for the anchors on the Town rows to change their text to '+'.
I've attempted to do so with
$(this).parent().parent().nextUntil(".TRBrand", ".TownToggle").text("+");
but try as I might it won't play nicely.
Can anyone point me in the right direction ...?
Nested lists are better for tree like structures. You can see the js is easier to write with this markup:
http://jsfiddle.net/RANmK/1/
There were several problems with your version:
The last <a> (for Reebok) had the wrong class : TRTown instead of TownToggle
Your nextUntil(...) for TownToggle was only stopping when it sees .TRTown, which means it hides too much when it is the last Town in the list and continues to hide the next brand as well. It should also stop on .TRBrasnd. You can specify both selectors by seperating them with a comma.
a.toggleTown was not targetted correctly when updating the text value to +
If I understand your requirements correctly, the following should do what you want: http://jsfiddle.net/Sx4qg/69/
$('.BrandToggle').click(function() {
var t = $(this);
var txt = t.text();
var tr = t.closest("tr");
if (txt == "+") {
tr.nextUntil(".TRBrand", ".TRTown").show();
} else {
tr.nextUntil(".TRBrand", ".TRTown, .TRShoes").hide();
tr.nextUntil(".TRBrand", ".TRTown").find("a.TownToggle").text("+");
}
t.text(txt == "+" ? "-" : "+");
});
$(".TownToggle").click(function() {
var t = $(this);
var txt = t.text();
var tr = t.closest("tr");
if (txt == "+") {
tr.nextUntil(".TRBrand,.TRTown", ".TRShoes").show();
} else {
tr.nextUntil(".TRBrand,.TRTown", ".TRShoes").hide();
}
t.text(txt == "+" ? "-" : "+");
});
Try this:
$(this).parent().parent().nextUntil(".TRBrand").find('.TownToggle').text("+");
http://jsfiddle.net/sangdol/Sx4qg/64/
Hope this fiddle will help
$(this).parent().parent().nextUntil("tr:not(.TRTown, .TRBrand)", ".TownToggle").text("+");
Related
I have a bit of javascript / jquery that upon pressing "enter" in a search box goes through all table rows and then hides those which are not applicable/ do not contain the string. This process is however is extremely taxing on slower systems and so I decided to implement a small loading gif so people know something is happening even though it seems the browser has frozen. The problem though is that the image never appears. I'm assuming it's because the browser freezes. So, now to my question. How can i either make the loop faster, use less computing power, and show the gif? Thank you very much
var $rows = $('tbody tr.visall');
$('#search').keydown(function(e) {
if (e.keyCode == 13){
$('.load').show();
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
};
$('.load').hide();
});
edit: this code goes through about 9000-10000 tr elements.
Hard to say if it will be enough for your data. But here is what you can do:
Reduce the amount of dom manipulations. You can add|remove class hidden to show hide rows.
If your text is static you can create text cache and do not extract it on every search.
You can use setTimeout to delay search execution to show loading gif. Not even sure you will need one. Searching in memory is quite fast.
Demo.
Code
$(function() {
var table = $('#mytable'), //your table
rows = table.find('tr').map(function(){ //all rows you need
return $(this);
}),
rowsCache = (function(from){ //text cache
return from.map(function(){
return this.text();
});
}(rows));
function delay(func) { //delayed function executor
setTimeout(func, 13);
}
var load = $('#load'); //your loader
$('#search').keydown(function(e){
var val;
if(e.keyCode === 13) {
val = $.trim($(this).val());
load.show();
table.hide(); //release dom
delay(function() {
//search in text cache
var toShow = rowsCache.map(function(_, row) {
return row.indexOf(val) > -1;
});
rows.each(function(i){
//simply toggle class let css work for you
this.toggleClass('hidden', !toShow[i]);
});
load.hide();
table.show();
});
}
});
});
Personally I would say drop the filter and use CSS selectors instead then it's just basic DOM manipulation which jQuery should be optimized for.
See http://api.jquery.com/contains-selector/ for documentation and here is a little fiddle http://jsfiddle.net/tgz5X/
Here is what I use in the fiddle as a simple example
function search(mySearchValue) {
$("tr > td:contains(" + mySearchValue + ")").show();
$("tr > td:not(:contains(" + mySearchValue + "))").hide();
}
You would need more but you should get the idea behind this approach.
Or use filter still but with selectors, also this may trigger hide on element which will have show after so more DOM manipualtion
$("tr td").hide().filter(":contains(" + mySearchValue + ")").show();
i have a situation where i need to achieve this, in a table having n rows. if i click on a row in a table and then click on another row. the content in row of first click should go to content in row of second click and then each row should be shifted by on step backward or forward. this can be taken equivalent to JQUERY sortable.
Example:
|1|2|3|4| if i click on 1 and 4 then it should be |2|3|4|1|
how to record two clicks, and the contents of my rows are div elements containing many input elements. I thought of this idea and is this a good way to achieve sortable or is there a still better way, i want to do it using java script.
thanks in advance.
my script fucntion goes like this. I really should have thought for a little longer. i used flags here, i got two questions more, can i do that with out flags?, is there a better way?
<script>
var flag=0;
var id1;
var id2;
function Myfunction(id)
{
if(flag==0)
{
id1=id;
flag=1;
}
else
{
id2=id;
var x=document.getElementById(id1).innerHTML;
var num1=parseInt(id1);
var num2=parseInt(id2);
for(var i=num1;i<num2;i++)
{
var j=i.toString();
var k=(i+1).toString();
document.getElementById(j).innerHTML=document.getElementById(k).innerHTML;
}
document.getElementById(id2).innerHTML=x;
flag=0;
}
}
</script>
I made up a little http://jsfiddle.net/zxKeg/. Works with jQuery only, no additional plugins needed. Hope this will help you!
JS Code:
$(document).ready(function() {
var $table = $('table');
var $toCopy = null;
$table.on('click', 'tr', function() {
if($toCopy === null || $toCopy[0] == this) {
$toCopy = $(this);
}
else {
$toCopy.remove();
$(this).after($toCopy);
$toCopy = null;
}
});
});
So many times we want to limit how much a user can write, but here I have a special sized box that it has to fit in, so I want to disable adding more characters if it would surpass a specific height. here is what I did:
var over;
$('textarea').keypress(function(e){
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
var t = $(this).val();
jQuery('<div/>', {
style: "visibility:hidden",
text: t,
id: "test"
}).appendTo('body');
var h = $('#test').height();
if(h >= 100){
over = true;
}
else{
over = false;
}
if(over){
//code goes here
}
$('#test').remove();
});
I got the limiting code (what goes where I have the "code goes here" comment) from here and it ALMOST works.
There is only one problem:
if somebody copies and pastes, it can place multiple characters and therefore still go over the limit.
How can I fix this issue?
jsfiddle
Another somewhat hacky solution could be to check scroll on key up. If scroll exists, delete the last character while scroll exists:
function restrictScroll(e){
if(e.target.clientHeight<e.target.scrollHeight){
while(e.target.clientHeight<e.target.scrollHeight){
e.target.value = e.target.value.substring(0, e.target.value.length-1);
}
}
};
document.getElementById("textareaid").addEventListener('keyup', restrictScroll);
This would work as you type and if you paste blocks of text. Large text blocks may take a little longer to loop through though. In which case you may want to split on "\n" and remove lines first, then characters.
jsfiddle
If you want your function to fire whenever the text in your field changes, you can bind it to the input and propertychange events, as per this answer:
https://stackoverflow.com/a/5494697/20578
Like this:
$('#descrip').on('input propertychange', function(e){
This will make sure your code fires when e.g. the user pastes in content using the mouse.
As for stopping them from entering content that would go over the limit, I think you have to keep track of what content they've entered yourself, and then revert their last edit if it infringed your criteria.
Note that e.g. Twitter doesn't stop the user from entering more characters if they've gone over the limit - they just tell the user they're over the limit, and tell them when they're back under. That might be the most usable design.
You may try this:
$('#descrip').bind('paste',function(e) {
var el = $(this);
setTimeout(function() {
//Get text after pasting
var text = $(el).val();
//wath yu want to do
}, 100);
};
Jsfiddle
The solution is taken from here and here. It works by binding to the paste event. Since paste event is fired before the text is pasted, you need to use a setTimeout to catch the text after pasting. There is still some rough edges (i.e. if you select text and press backspace, it does not update).
Still, Spudley comment has some valid points, that you may want to consider.
Edit:
Note on the jsfiddle: It allow you to go over the limit when pasting, but once over the limits, you cannot paste (or type) more text until you go under the limit again.
Must be taken into account that, since you are limiting the text length by the size it ocuppies after rendering (wich have it own issues as pointed by Spudley), and not a defined lenth, you can know if a text fits or not, but not know how much of the text is inside the limits, and how much is out of them.
You may consider reseting textbox value to its previous value if pasted text makes imput go over the limit, like in this one.
However, for cutting down the text after pasting so as non-fitting text is left out, but the rest of the pasted text is allowed, you need an entirely different approach. You may try iterating over the text until you find how much of the new text is enough.
By the way, line feeds and seems to cause your original script to behave weirdly.
I've been able to get the program working:
var over = false;
var num = 0;
var valid_entry = "";
$('#descrip').keyup(function(e){
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
var t = $(this).val();
getMaxRow(t,key,this);
});
function getMaxRow(t,key,obj) {
jQuery('<div/>', {
"class": "hide",
text: t,
id: "test"
}).appendTo('body');
var h = $('#test').height();
$('#test').remove();
if(h >= 100){
num += 1;
if(num == 1){
var div = '<div id="message">You have run out of room</div>'
$('body').append(div);
}
over = true;
}
else{
over = false;
valid_entry = t;
if(num >= 1){
$('#message').remove();
num = 0;
}
}
if( over ) {
//Do this for copy and paste event:
while ( over ) {
//Try using a substring here
t = t.substr(0,(t.length-1));
over = getMaxRow(t,key,obj);
}
}
$(obj).val(valid_entry);
return over;
}
Looking for some help on how to write a function to filter out certain divs with certain classes.
Essentially I have thrown together a quick e-commerce example. There are lists of different filters, with values. There are then products. Each product div has a number of classes applied to it, e.g "green" or "adult" or "wool" - these are the filterable parameters.
Not being savvy at all with JS I'm trying to write something, but looking for some advice. Here is basically what I'm after:
Starts with displaying all
If user selects GREEN, all items that do not have GREEN attributed are display:none'd (with a fade transition
Rep #2 for any attribute checked
Notes: multiple attributes can be checked, when items are unchecked, everything needs to reappear.
Any help? I guess it's basically linking up the value of each checkbox to the class.
Not sure if there is a better way codewise to do this... data attributes maybe?
Working example of the code here (obviously no JS)
Updated your fiddle and added some jQuery to hide the divs where the classes don't match the selected checkboxes.
Demo: fiddle
JS is a bit verbose, you can refactor it further if you like:
$(document).ready(function() {
var allSelectedClasses;
allSelectedClasses = '';
$('input[type="checkbox"]').click(function(){
//ensure the correct classes are added to the running list
if(this.checked){
allSelectedClasses += '.' + $(this).val();
}else{
allSelectedClasses = allSelectedClasses.replace($(this).val(), '');
}
//format the list of classes
allSelectedClasses = allSelectedClasses.replace(' ', '');
allSelectedClasses = allSelectedClasses.replace('..', '.');
var selectedClasses;
var allSelected;
allSelected = '';
//format these for the jquery selector
selectedClasses = allSelectedClasses.split(".");
for(var i=0;i < selectedClasses.length;i++){
var item = selectedClasses[i];
if(item.length > 0){
if(allSelected.length == 0){
allSelected += '.' + item;
}else{
allSelected += ', .' + item;
}
}
}
//show all divs by default
$("div.prodGrid > div").show();
//hide the necessary ones, include the 2 top level divs to prevent them hiding as well
if(allSelected.length > 0){
$("div.prodGrid > div:not(" + allSelected + ")").hide();
}
});
});
I added a new class to your Colors ul. Hope that's okay.
Here's a crude version of a filtering function, it only takes colors into account so you have to modify it yourself to take everything into account but the basic outline is there.
It can be refactored massively! :)
Since you're using jQuery:
$('ul.colorFilter li input[type="checkbox"]').click(function(){
var checkedBoxes = $('ul.colorFilter li input[type="checkbox"]:checked');
var listOfClasses = [];
checkedBoxes.each(function(index, el){
listOfClasses.push(el.value);
});
if(listOfClasses.length >= 1){
$('div.prodGrid').children('div').hide();
for(var i = 0; i < listOfClasses.length; i++){
$('div.prodGrid > div.'+listOfClasses[i]).show();
}
} else {
$('div.prodGrid > div').show();
}
});
I made a fiddle as well:
http://jsfiddle.net/Z9ZVk/4/
Made a fiddle: http://jsfiddle.net/n6ub3/
I'm aware that the code has a LOT of repeating in it, its on the list to refactor once functionality is correct.
The behaviour i'm trying to achieve is if there is no selectedTab on page load, set the first tab in each group to selectedTab. If there is a selectedTab present, then use this as the default shown div.
However, as you can see from the fiddle its not working as planned!
If anyone has any ideas how to refactor this code down that'd be great also!
Change
if($('.tabs1 .tabTrigger:not(.selectedTab)')){
$('.tabs1 .tabTrigger:first').addClass('selectedTab');
}
to
if ( !$('.tabs1 .tabTrigger.selectedTab').length ) {
$('.tabs1 .tabTrigger:first').addClass('selectedTab');
}
Demo at http://jsfiddle.net/n6ub3/1/
They way you are doing it (the first code part) you are adding the .selectedTab class if there is at least one of the tabs in that group that is not selected at start .. (that means always)
Update
For a shortened version look at http://jsfiddle.net/n6ub3/7/
Your selector are doing exactly what you're writing them for.
$('.tabs3 .tabTrigger:not(.selectedTab)') is true has long as there is at least one tab that has not the selected tab (so always true in your test case).
So you should change the logic to !$('.tabs3 .tabTrigger.selectedTab').length which is true only if there are no selectedTab
WORKING DEMO with simplified code
$('.tabContent').hide();
$('.tabs').each(function(){
var search = $(this).find('div.selectedTab').length;
if( search === 0){
$(this).find('.tabTrigger').eq(0).addClass('selectedTab')
}
var selectedIndex = $(this).find('.selectedTab').index();
$(this).find('.tabContent').eq(selectedIndex).show();
});
$('.tabTrigger').click(function(){
var ind = $(this).index();
$(this).addClass('selectedTab').siblings().removeClass('selectedTab');
$(this).parent().find('.tabContent').eq(ind).fadeIn(700).siblings('.tabContent').hide();
});
That's all! You don't need all that ID's all around. Look at the demo!
With a couple of very minor changes you code can be reduced to:
$('.tabContent').hide();
$('.tabs').each(function(){
if($('.tabTrigger.selectedTab',$(this)).length < 1)
$('.tabTrigger:first').addClass('selectedTab');
});
$('.tabTrigger').click(function(){
var content = $(this).data('content');
$(this).parents('div').children('.tabContent').hide();
$(this).parents('div').children('.tabTrigger').removeClass('selectedTab');
$(this).addClass('selectedTab');
$('#' + content).show();
});
$('.tabTrigger.selectedTab').click();
Those changes are
Change the class on the surrounding div to just class="tabs.
Add a data-content attribute with the name of the associated content div
Live example: http://jsfiddle.net/gsTBQ/
Well, I'm a bit behind the times obviously; but, here's my updated version of your demo...
I have updated your fiddle as in the following fiddle: http://jsfiddle.net/4y3Xp/1/.
Basically I just tidied it up a bit, and to refactor I put everything in a separate function instead of having each of the cases in their own. This is basically just putting a new function in that does similar to what yours was doing (e.g. not modifying your HTML model), but I tried to clean it up a bit, and I also just made a function that took the tab number and did each of the items that way rather than needing a separate copy for each.
The main issue with the 'not' part of your query is that the function doesn't return a boolean; like all JQuery queries, it's returning all matching nodes. I just updated that part to return whether .selected was returning more than 0 results; if not, I go ahead and call the code to select the first panel.
Glad you got your problem resolved :)
$(document).ready(function(){
var HandleOne = function (i) {
var idxString = i.toString();
var tabName = '.tabs' + idxString;
var tabContent = tabName + ' .tabContent';
$(tabContent).hide();
var hasSelected = $(tabName + ' .tabTrigger.selectedTab').length > 0;
if (!hasSelected)
$(tabName + ' .tabTrigger:first').addClass('selectedTab');
var selectedTabId =
$(tabName + ' .tabTrigger.selectedTab').attr('id');
var selectedContentId = selectedTabId.replace('tab','content');
$('#' + selectedContentId).show();
$(tabName + ' .tabTrigger').click(function() {
$(tabName + ' .tabTrigger').removeClass('selectedTab');
$(tabName + ' .tabContent').hide();
$(this).addClass('selectedTab');
var newContentId = $(this).attr('id').replace('tab','content');
$('#' + newContentId).show();
});
}
HandleOne(1);
HandleOne(2);
HandleOne(3);
});