Slide dynamically added content with jQuery - javascript

I'm trying to create a simple content slider that could handle dynamically added content to the slider. None of the "lightweight" plugins I found provided such functionality or, if it did, it didn't work correctly.
var $left = $('.left'),
$right = $('.right'),
$months = $('.sub ul');
$left.click(function(){
for(i = 0; i < 3; i++){
$months.find('li').first().before($.parseHTML('<li>xxx</li>'));
}
pos = $months.position();
$months.css('left', pos.left + 90);
});
$right.click(function(){
for(i = 0; i < 3; i++){
$months.find('li').last().after($.parseHTML('<li>xxx</li>'));
}
pos = $months.position();
$months.css('left', pos.left - 90);
});
This is the code I've got so far and here's a fiddle with an example - http://jsfiddle.net/kkr4zg0r/2/. It kind of works, but the problem is that since new content is added the navigation goes off (you can see what I mean by clicking left-right a couple of times).
I understand what's the problem for this - the newly added items "shift" the content and I need to do better calculations than substracting/adding 90px to the left position of the element but I can't figure out how to get the correct index of the elements and basically get this sliding by exactly (and correctly) by 3(or 6) elements at the time.
Currently the code is adding extra elements whenever a navigation button is pressed, if I could get the index of the currently visible first/last element, I could probably tell whether I need to add more elements and only add them then.
This is a basic illustration of what I'm trying to achieve
edit
I've changed the jsfiddle to the correct one.

The whole idea is to check when adding elements is necessary and when shift is enough:
Fiddle
$(document).ready(function()
{
var $main = $('.main'),
$left = $('.left'),
$right = $('.right'),
$months = $('.sub ul');
var addCount = 3;
var liWidth = 30;
var shiftX = addCount * liWidth;
$left.click(function()
{
var currentLeft = parseInt($months.css('left'));
var totalLength = $months.find('li').length * liWidth;
if (-currentLeft + $main.width() >= totalLength)
{
for (var i = 0; i < addCount; i++)
{
$months.find('li:last').after('<li>xxx</li>');
}
}
$months.css('left', currentLeft -= shiftX);
});
$right.click(function()
{
var currentLeft = parseInt($months.css('left'));
if (currentLeft < 0)
{
$months.css('left', currentLeft += shiftX);
}
else
{
for (var i = 0; i < addCount; i++)
{
$months.find('li:first').before('<li>xxx</li>');
}
}
});
});

Related

arrange the div in sequence format using javascript

I am working on scenario where when I enter number in the textbox i need generate dynamically div's. Actually I am struggling not aligned properly with the current div. Then I need to generate ID's for the div's. For this also code is available but the code not considered the default div as preview1 then it has to go on like preview2, preview3 so on. The div has to arrange sequence like first it has to show preview1......
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function () {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.innerHTML = [1 + totalCount];
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
prevPage.className = "preview_windowSize";
prevPage.setAttribute('id', ['page' + totalCount]);
prevPage.appendChild(spancount);
prevPage.style.position = "absolute";
preview_PageSize.appendChild(prevPage);
//fragment.appendChild(prevPage);
fragment.appendChild(navbutton);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the fiddle Link
Thanks in advance.
Kindly help me.
if I get you right, change the javascript as follows:
//prevPage.style.position="absolute";
//preview_PageSize.appendChild(prevPage);
prevPage.style.width="100%";
preview_PageSize.parentNode.insertBefore(prevPage, preview_PageSize);
to improve positioning, you could apply a diffrent class to the child elements, like so:
prevPage.className = "preview_windowSize_element";
and use CSS:
.preview_windowSize_element {
position: absolute;
left: 31px;
top: 0px;
width: 100%;
height: 100%;
}
to start with page ID 1 you could modify your script:
prevPage.setAttribute('id', ['page' + (totalCount + 1)]);
Do you search something like this jsFiddle?.
I just add a left position in each div, because you set them to position:absolute.
So I added this line:
prevPage.style.left= (26 * totalCount) + "px";
I just put 26 like this, it will be the width of the button

How do I set the interval in a for loop?

I'm trying to create a menu of social media icons that slides into and out of the page. The following code works, but it is too fast. It doesn't look like sliding. I think I could adjust the timing using the setInterval() method, but I can't get it to work. This is the code so far:
var socialMedia = document.getElementById("socialmedia");
var stalkMe = document.getElementById("pleasestalkme");
function SM() {
socialMedia.style.position = "fixed";
socialMedia.style.right = "-330px";
}
SM();
stalkMe.addEventListener("click", function(){
if (socialMedia.style.right === "-330px") {
for (i = -330; i <= -30; i++) {
var j = i +"px";
socialMedia.style.right = j;
}
} else if (socialMedia.style.right === "-30px"){
for (i = -30; i >= -330; i--){
var j = i +"px";
socialMedia.style.right = j;
}
}
}, false);
You should have a look at CSS transitions. Basically you just need to change the right style from 300px to 0px and using transition: right 1s; you would see your element being animated
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Otherwise, you could have a look at jQuery.... (I feel bad).
Prior to the solution, a word of warning: you actually should not use this code snippet. Instead heed the advice of floribon and look into css transitions.
However, if you absolutely must do it the outmoded way:
for (i = -330; i <= -30; i++) {
var j = i +"px";
socialMedia.style.right = j;
}
write
var hnd;
i = -330;
hnd = setInterval ( function () {
var j = i +"px";
socialMedia.style.right = j;
i++;
if (i > -30) {
clearInterval(hnd); // end activity
}
}, 50 ); // interval length in ms

Javascript not entering a FOR loop inside a function

I came here a few days ago asking for help on creating a grid of squares in JS/CSS.
A very helpful person came here and guided me on using two nested fors and createElement('div'); to get the job done. However, his example was a code that went directly into doing that: http://jsfiddle.net/3x1kmcme/
I need the action to actually happen when the user clicks a button, using a .click() JQuery function. This is not working, and no error is being shown. I really did try going through the code itself, and even changed it, declared it beforehand as a variable, and went line by line to check where the error lies, it seems it's not entering the FOR loop, I could be wrong, of course.
Perhaps something obvious I'm missing?
var rows = 8,
cells = 8,
count = 0;
var i, j,
top = 0,
left = 0;
var boxWidth = 50,
boxHeight = 50;
var $canvas = $('#canvas');
var $fragment = $(document.createDocumentFragment());
$(document).ready(function () {
"use strict";
$("#btnstart").click(function () {
function addBox(opts) {
var div = document.createElement('div');
div.id = opts.id;
div.className = 'alive';
div.style.top = opts.top + "px";
div.style.left = opts.left + "px";
$fragment.append(div);
}
for (j = 0; j < rows; j += 1) {
top = j * boxHeight;
for (i = 0; i < cells; i += 1) {
count += 1;
addBox({
count: count,
id: 'item' + i,
top: top,
left: i * boxWidth
});
}
}
$canvas.html($fragment);
});
});
It seems to work just fine at the following fiddle
Not really sure what exactly the problem is. I added the following changes to the HTML
<div id="canvas"></div>
<input type='button' id='btnstart' value='Start' />
I figured out the problem AND the reason why it worked on JSFiddle. Even if I wrapped the JavaScript file in a Document.Ready function, I still had to put the scripts at the bottom of the page, just below the tag.

Adding / removing classes when scrolling on multiple elements

I was using a script (that I probably found here) to add / remove classes on elements while scrolling. The scripts associates href from a menu to add / remove classes to corresponding element in the page. The script works fine when using one menu and one set of elements, but I tried to make it usable with multiple menus and I can't seem to find what's wrong. I get an error with the getTargetTop() function, but I can't resolve it.
Here is the code I'm using :
$(window).scroll(function(e){
checkSectionSelected($(window).scrollTop());
});
function getTargetTop(elem){
console.log(elem.attr('href'));
var id = elem.attr("href");
var offset = 0;
return $(id).offset().top - offset;
}
var sections = $('ul.ctrl a');
var mainmenu = $('nav a');
function checkSectionSelected(scrolledTo){
var threshold = 100;
var i;
for (i = 0; i < sections.length; i++) {
var section = $(sections[i]);
var target = getTargetTop(section);
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
$('.char').removeClass('active');
$('.char'+section.attr('href')).addClass('active');
sections.parent('li').siblings('li').removeClass("active");
section.parent('li').addClass("active");
}
};
var m;
for (m = 0; m < mainmenu.length; m++) {
var link = $(mainmenu[m]);
var newTar = getTargetTop(link);
if (scrolledTo > newTar - threshold && scrolledTo < newTar + threshold) {
sections.parent('li').siblings('li').removeClass("active");
section.parent('li').addClass("active");
}
};
}
Thanks for helping!

How would I write a variable to call all margins on all elements on the page with Jquery?

Title pretty much says it all, I duno if this is basic or advanced but I need a variable that will be the sum of all top and bottom margins of every element on the page that has margins. I don't need the left or right ones. Can this be done easily?
Try this:
function sumMargins() {
var total = 0;
$("*").each(function() {
var top = parseInt($(this).css("marginTop"));
var bottom = parseInt($(this).css("marginBottom"));
total += (top + bottom);
});
return total;
}
See this fiddle.
var x = 0;
$('*').each(function() {
x += parseInt($(this).css('margin-top'));
x += parseInt($(this).css('margin-bottom'));
});
alert(x);
Here is a working fiddle:
http://jsfiddle.net/jonigiuro/qQ6sB/
function allMargins() {
var total = 0;
$('.container *').each(function(i) {
var currentTop = parseInt($(this).css('margin-top'));
var currentBottom = parseInt($(this).css('margin-bottom'));
total = total + currentTop + currentBottom;
});
return total;
}
alert('The total of the margins is: ' + allMargins());
I added a .container div to limit the * selector, otherwise it would also include the html and the body tags, which are not consistent about the margin (I had 8 pixels).
The solutions above are faster, but this is more solid.

Categories