I'm trying to implement multiple scrollbars with the plugin Tinyscrollabr.js
http://baijs.nl/tinyscrollbar/
To implement the scrollbars, i use a function scrollify like in this article :
http://www.eccesignum.org/blog/making-tinyscrollbarjs-easier-to-implement
HTML :
<ul id="myList">
<li id="scrollbar1" class="col">
<h2>Title 01</h2>
<div class="scrollBox"><!--Scrollable Content here--></div>
</li>
<li id="scrollbar2 class="col">
<h2>Title 02</h2>
<div class="scrollBox"><!--Scrollable Content here--></div>
</li>
<li id="scrollbar3 class="col">
<h2>Title 03</h2>
<div class="scrollBox"><!--Scrollable Content here--></div>
</li>
</ul>
Javascript :
function scrollify(element,options) { // '#element', {list:of,key:values}
var opt = options || {}
$(element).children().wrapAll('<div class="viewport"><div class="overview"></div></div>');
$(element).prepend('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
$(element).tinyscrollbar(options);}
$scrollbar1 = $('#scrollbar1 .scrollBox') ;
$scrollbar2 = $('#scrollbar2 .scrollBox');
$scrollbar3 = $('#scrollbar3 .scrollBox');
$scrollbar4 = $('#scrollbar4 .scrollBox');
$(function() {
scrollify($scrollbar1);
scrollify($scrollbar2);
scrollify($scrollbar3);
scrollify($scrollbar4);
})
I would to make this more simple.
For example, i would to be able to make this :
$(function() {
scrollify('.scrollBox');
})
But tinyscrollbar need an id. With a class, it's load the first scrollbar and not the others. Firebug return this error message "f.obj[0] is undefined"
Sorry if my question is stupid, but how can I do for applying tinyscrollbar to a list of elements with a class ?
And then, after some actions how to update all this scrollbars with the function $allScrollbars.tinyscrollbar_update();
Thanks for help, I'm just beginning with javascript and i'm trying to learn.
I would count the number of elements with the class:
var scrollCount = $(".scrollbox").size();
Then use an iterating loop to call each of your IDs:
for (i=0; i<5; i++) {
scrollify($('#scrollbar' + i));
}
Also I would recommend using DIVs instead of the list setup you have, use the example from the link you shared as a starting point :)
Thanks KneeSkrap3r for your answer. It's a good solution to make this but i'm trying to do something in the case i' don't know the numbers of element to scroll.
I think I've found with something like this (it's a part from the first jquery plugin i'm trying to do ) where $el is all elemnts with the class"scrollbox".
$el.each(function(index)
{
var $scrolls = $(this);
function scrollify(element,options)
{ // '#element', {list:of,key:values}
var opt = options || {}
$(element).children().wrapAll('<div class="viewport"><div class="overview"></div></div>');
$(element).prepend('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
$(element).tinyscrollbar(options);
}
scrollify($scrolls);
// Update heights
$(window).resize(function()
{ $scrolls.tinyscrollbar_update('relative');
});
})
Like this, it's seems to work but i don't know if i'm using good practice of javascript.
For the Html markup, I told the li elements for div, it's better for the semantic.
Thanks for tips ;-)
Related
So I have this HTML here generated by Wordpress. I want to select the DIVs seperately using JS. Is this possible? Can I maybe select them by the order on which JS finds them in my HTML?
I tried if something like this would be possible (By adding an index number) but I believe that is used only for the LI element. But you get the idea. The end result is to add a different classname to each div object using .className
var koffie = document.getElementsByClassName("g-gridstatistic-item-text2")[0];
var brain = document.getElementsByClassName("g-gridstatistic-item-text2")[1];
var tevred = document.getElementsByClassName("g-gridstatistic-item-text2")[2];
console.log(koffie);
console.log(brain);
console.log(tevred);
<div class="g-gridstatistic-wrapper g-gridstatistic-3cols">
<div class="g-gridstatistic-item">
<div class="g-gridstatistic-item-wrapper">
<div class="g-gridstatistic-item-text1 odometer" data-odometer-value="4"></div>
<div class="g-gridstatistic-item-text2">Kopjes koffie per dag</div>
</div>
</div>
<div class="g-gridstatistic-item">
<div class="g-gridstatistic-item-wrapper">
<div class="g-gridstatistic-item-text1 odometer" data-odometer-value="14"></div>
<div class="g-gridstatistic-item-text2">Brainstormsessies per week</div>
</div>
</div>
<div class="g-gridstatistic-item">
<div class="g-gridstatistic-item-wrapper">
<div class="g-gridstatistic-item-text1 odometer" data-odometer-value="12"></div>
<div class="g-gridstatistic-item-text2">Tevreden klanten</div>
</div>
Your JavaScript code is looking for DOM elements before it checks whether the DOM has even loaded. Try wrapping it in an event listener, like so:
JS
document.addEventListener('DOMContentLoaded', function () {
var koffie = document.getElementsByClassName("g-gridstatistic-item-text2")[0];
var brain = document.getElementsByClassName("g-gridstatistic-item-text2")[1];
var tevred = document.getElementsByClassName("g-gridstatistic-item-text2")[2];
//console.log(koffie);
//console.log(brain);
//console.log(tevred);
/* to evidence that targeting works: */
brain.classList.add('addedClass');
});
CSS
.addedClass {
font-size:22px;
color:red;
}
Full demo here:
https://jsbin.com/saxizeyabo/edit?html,css,js,console,output
simply like this
var yourVariableName = document.getElementsByClassName("g-gridstatistic-item-text2");
console.log(youVariableName[0]);
console.log(youVariableName[1]);
and so on like an array
document.querySelectorAll('.g-gridstatistic-item-text2').item(0);
https://developer.mozilla.org/de/docs/Web/API/Document/querySelectorAll
This way, you can just use CSS-Selectors
The below code should work.
var classes = document.getElementsByClassName('g-gridstatistic-item-text2');
for(var i=0; i<=classes.length; i++) {
var appendClass = 'your_class_name'+i;
classes[i].classList.add(appendClass);
}
I have a cshtml view file with the following code:
<ul id="ul1">
<li id="ul1li1"></li>
<li id="ul1li2"></li>
<li id="ul1li3"></li>
</ul>
And an action "x" which returns me html code with which is several divs one after the other.
something like :
<div class="xdiv"></div>
<div class="xdiv"></div>
<div class="xdiv"></div>
<div class="xdiv"></div>
<div class="xdiv"></div>
Id like to use javascript function in order to put the divs I get from the action "X", into the lis in a circular ascending order.
I couldn't find the right solution, and so far my javascript function is something like this :
function fillLis()
{
var i = 0;
divs = #Url.Action("X");
for(ind in divs){
div = divs[ind];
i = i%3 + 1;
var currentli = document.getElementById('ul1li'+i);
currentli.innterHTML += div.innerHTML;
}
};
Because of some bad html coding, I have to do it that way.
This isn't doing what you think:
divs = #Url.Action("X");
It's just going to resolve to a string (and a syntax error), such as:
divs = /Home/X;
What you want to do is make an AJAX request to that action. (Note: Since you're using ASP.NET, I'm assuming that jQuery is an option.) Something like this:
$.get('#Url.Action("X")', function (data) {
// update your UI
});
In that callback function, data will contain the response from the server. Which, in this case, should be the HTML. At this point it looks like you want to loop over the div elements. So you can probably wrap it in a jQuery object and loop over that. Something like this:
$.get('#Url.Action("X")', function (data) {
var divs = $('div', data);
// at this point "divs" is a list of div HTML elements in the response
});
Your existing code should work on the divs array, perhaps with some minor adjustments through debugging. But essentially that's how you'd get the HTML elements you're looking for from the server in order to use those elements in your client-side code.
Something like that?
Array.prototype.forEach.call(#Url.Action("X"), function(xdiv, i) {
document.getElementById("ul1li"+i).appendChild(xdiv);
});
If not then please update your question with more detailed informations about what you're trying to do.
Some quick notes about your code:
function fillLis()
{
var i = 0;
divs = #Url.Action("X");
for(ind in divs){
div = divs[ind];
// This will always be equal to 1
i = i%3 + 1;
// You say you want to "put the divs [...] into the list", but it seems like you're trying to transfer only the content of your divs
var currentli = document.getElementById('ul1li'+i);
currentli.innterHTML += div.innerHTML;
}
};
I have following problem. Let's say I have DOM like this.
<div class="results">
<div class="result">
<div class="title">Aaa</div>
</div>
<div class="result filtered-out">
<div class="title">Aab</div>
</div>
<div class="result">
<div class="title">Aac</div>
</div>
<div class="result">
<div class="title">Aad</div>
</div>
<div class="result">
<div class="title">Aae</div>
</div>
</div>
and an input field like this
<input type="text" id="search">
And now I try to filter the results with a simple function defined by this
var searchBox = $(this);
searchBox.keyup(function(){
var searchBox = $(this);
var items = $(".results .result:not(.filtered-out)");
items.each(function(){
var title = $(this).find(".title").html();
if(title.toLowerCase().indexOf(searchBox.val().toLowerCase())!== -1)
$(this).show();
else
$(this).hide();
});
});
So the problem is that the list of results is quite long something between 100 and 200 elements and whenever I type something into the search input the code executes very long. Maybe around 2-3 seconds. Is there any other approach to solve this "lag"? Thank you for any advices!
EDIT Maybe something like delayed script execution or asynchronous script execution (like in ajax)?
It's generally not a good idea to use the DOM as a datasource, it's not meant for it and is therefore slow. Personally I would recommend using a small MVVM library or something similar so you don't have to manually manage the DOM yourself.
I've used Vue.js below, but you could just as well use any similar solution. Keeping your data in the code will allow you to operate on it a lot faster since you don't have to re-request it all the time and you avoid doing a lot of work for modifications. All operations below are done on 1000 objects:
var items = [];
for (var i = 0; i < 1000; i++) {
items.push({
title: 'Item #' + i
});
}
var v = new Vue({
el: '#list',
data: {
items: items,
input: ""
},
computed: {
filteredItems: function() {
var value = ("" || this.input).trim().toLowerCase();
if (!value.length) return this.items;
return this.items.filter(function(item) {
return item.title.toLowerCase().indexOf(value) !== -1;
});
}
}
});
ol {
list-style: none;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
<div id="list">
<input placeholder="Search" v-model="input" />
<ol>
<li v-repeat="filteredItems">{{title}}</li>
</ol>
</div>
When searching the dom through many elements it is recommended to use javascript as opposed to jQuery if speed is what you are after. jQuery has it's purpose but for large amounts of dom searching using javascripts getElementById or querySelector / querySelectorAll is going to be much much faster. If you check this jsPerf example you can see that the jQuery selector operates roughly 94% slower than the comparable getElementById.
You should try using some logging to figure out which part is taking the longest. If you find that it's the items selector (with the psuedo-not), you could try to optimize that, however I don't see anything about the filtered-out class so I'm not sure exactly what that does.
Here's some simple optimizations though:
var searchBox = $(this);
searchBox.keyup(function(){
var $searchBox = $(this);
var searchBoxVal = $searchBox.val().toLowerCase();
var items = $(".results .result:not(.filtered-out)");
items.each(function(){
var $item = $(this);
var title = $item.find(".title").html();
if (title.toLowerCase().indexOf(searchBoxVal) !== -1)
$item.show();
else
$item.hide();
});
});
My guess the lag is because you are performing the search based on the DOM elements, and at the same time manipulating them with hiding/ showing.
I suppose the DOM is populated from some data source? If so it'll be better to perform the search/ filter from that data source, then use the filtered data set to populate the DOM again. (And even if you don't have the data source at first, you can build one by reading the original DOM)
I've searched through StackOverflow for what I regard as a basic issue, but I could not find any relevant threads. Mainly because I feel like I am searching for the wrong keywords.
I would like to know how the summarize the next bit into as few lines of code as possible. When you click on 'link-#', it loads the content from the hidden div 'more-#' (where the # in more could be any number, but is the same as the number in link-#.) Right now I have this:
jQuery("#link-1").click(function(){
jQuery('#more').hide().html($('#more-1').html()).fadeIn(400)
});
jQuery("#link-2").click(function(){
jQuery('#more').hide().html($('#more-2').html()).fadeIn(400)
});
jQuery("#link-3").click(function(){
jQuery('#more').hide().html($('#more-3').html()).fadeIn(400)
});
etc.
I assume it should be something like below, but obviously it's not the correct way.
jQuery("#link" + NUMBER ).click(function(){
jQuery('#more').hide().html($('#more-' + this.NUMBER).html()).fadeIn(400)
});
I bet you guys know exactly how to deal with this! Thank you for your help.
Best regards,
Thomas
A preferable approach is to group these items by giving them the same class, and use a data-* attribute to identify the associated element:
jQuery(function() {
jQuery(".show-more").click(function() {
var target = $(this).data('target');
jQuery('#more').hide().html($(target).html()).fadeIn(400);
});
});
#moreItems {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Show More 1
Show More 2
Show More 3
<div id="more"></div>
<div id="moreItems">
<div id="more-1">Here are the details 1</div>
<div id="more-2">Here are the details 2</div>
<div id="more-3">Here are the details 3</div>
</div>
Give them all the same class name and then add the attribute "data-num" and then:
jQuery(".className").click(function () {
var $this = $(this);
var html = jQuery('#more' + $this.attr('data-num')).html();
jQuery('#more').hide().html(html);
});
Example HTML:
<a class='className' data-num='1'>Link</a>
<div id='more1'></div>
<div id='more'></div>
I am working with a WordPress theme and this is the functionality that I am trying to achieve:
225-1077
It sure is easily done with HTML but I am really not good with WordPress and this theme I got has so much files in it that it's hard to find where I should edit however, the theme allows you to add custom JS so I was wondering if the functionality above can be done with JS.
Any help is very much appreciated!
Very simply, it is possible, but that doesn't mean it's a good idea. JS support across mobile phones is not consistent, and not even always enabled, which would mean that these people would never see your link.
To create the link with JS is simple :
var cta = document.createElement('a');
cta.href = 'tel:12341234';
cta.setAttribute('class', 'my cta classes');
cta.appendChild(document.createTextNode('1234-1234'));
and then you need to put it somewhere on the page. If we have <div>s all over the place with a specific class, we can use that:
This is our HTML
<div class="target-cta">This div should receive a link</div>
<div class=""> this one shouldn't </div>
<div class="target-cta"> should have one here </div>
<div class=""> ...though not here</div>
<div class="target-cta">and finally, one here:</div>
and our JS to insert the links should loop through these elements, creating the links and inserting them as it goes:
var targets = document.getElementsByClassName('target-cta'),
target,
i,
cta; // Call To Action
for (i = 0; i < targets.length; i++) {
target = targets[i];
cta = document.createElement('a');
cta.href = 'tel:12341234';
cta.setAttribute('class', 'my cta classes');
cta.appendChild(document.createTextNode('1234-1234'));
target.appendChild(cta);
};
var targets = document.getElementsByClassName('target-cta'),
target, i, cta;
for (i = 0; i < targets.length; i++) {
target = targets[i];
cta = document.createElement('a');
cta.href = 'tel:12341234';
cta.setAttribute('class', 'my cta classes');
cta.appendChild(document.createTextNode('1234-1234'));
target.appendChild(cta);
};
<div class="target-cta">This div should receive a link</div>
<div class=""> this one shouldn't </div>
<div class="target-cta"> should have one here </div>
<div class=""> ...though not here</div>
<div class="target-cta">and finally, one here:</div>