So I have two divs and inside there gona be some blocks:
<div class="list-block 01">
<span>21#epos.com</span>
<span class="moveSym" id="01">+</span>
</div>
if one clicks on
+
whole block moves to other div.
Everything works but only to move ech block to another div once,
but I need them to go both ways as much as .moveSym clicked.
my JS
//remove block on click
$('.del-block').on('click', function() {
var block = $(this).attr('id');
$('.' + block).remove();
})
//move form list blocks to different fields
$('.leftSide01 .moveSym').click(function() {
console.log($(this).attr('id'));
var id = $(this).attr('id');
$(this).text("-");
$('.leftSide01 .list-block.' + id).appendTo('.rightSide01');
})
$('.rightSide01 .moveSym').click(function() {
console.log($(this).attr('id'));
var id = $(this).attr('id');
$(this).text("+");
$('.rightSide01 .list-block.' + id).appendTo('.leftSide01');
})
I know there are plugins for this, but I really want to write it by myself and learn :)
Fiddle http://jsfiddle.net/A1ex5andr/CRvVK/
Need to use event delegation, because the handler to be executed depends on the parent element.
//move form list blocks to different fields
$('.leftSide01').on('click', '.moveSym', function () {
console.log($(this).attr('id'));
var id = $(this).attr('id');
$(this).text("-");
$('.leftSide01 .list-block.' + id).appendTo('.rightSide01');
})
$('.rightSide01').on('click', '.moveSym', function () {
console.log($(this).attr('id'));
var id = $(this).attr('id');
$(this).text("+");
$('.rightSide01 .list-block.' + id).appendTo('.leftSide01');
})
Demo: Fiddle
You can really simplify this logic into one function that works for both (if there are only ever going to be two divs) . . .
$('.moveSym').click(function() {
console.log($(this).attr('id')); // I just left in, because you had it in the original code :)
var targetParent = $(".rightSide01");
var linkText = "-";
if ($(this).parent(".rigthSide01") > 0) {
linkText = "+";
targetParent = $(".leftSide01");
}
$(this).text(linkText);
$(this).parent().appendTo(targetParent);
});
This code starts out assuming that the block is on the left-hand side . . . it sets up the targetParent value (i.e., where the block will move to) to the right-hand side and the new link text to be "-".
After that, it checks to see if the block is actually on the right-hand side, instead, and, if it is, then it updates the variables with the values needed to move it to the left.
At that point, it updates the text in the "move-sym" span element to the final linkText value, and moves its parent block to the new target div (the targetParent value).
No need to worry about the delegation or event handlers in this one, because the function is the same, regardless of the location, and will travel with the "move-sym" span element, wherever it goes.
Related
I have simple Database, which contains fields like ID, product_name, product_description, image, cost.
I have a dynamically generated form which I'm going to send using jQuery, what should I change in my JavaScript to pass to defined div the data which I got from my DB via PHP?
JavaScript Code:
$(function() {
var number = 1;
var contentToLoad = 'Defined structure';
$('a.add').click(function(e) {
e.preventDefault();
$('#calc').append(contentToLoad);
number++;
});
$('#calc').on('click', 'a.design_button', function(e) {
e.preventDefault();
$(this).parent().remove();
});
});
---
UPDATE:
I need a little help with merging two parts of JavaScripts to make it work. I need to put somehow that part:
var number = 1;
var contentToLoad = 'Defined structure';
$('a.add').click(function(e) {
e.preventDefault();
$('#calc').append(contentToLoad);
number++;
});
where a.add i've replaced with submit button, inside this one
function add(data_array){
$(document).on('submit', '#add', function()
{
var r_data = data_array;
alert(r_data);
...
});
}
but I can't make it work ;/
I've menaged to do sth like that:
function mini(data_array){
var number = 1;
var r_arr = data_array;
$(this).on('submit', function(e) {
e.preventDefault();
var contentToLoad = '<div id="item-'+ number +'" class="item row"> '+ number +' '+r_arr+' Defined structure </div>';
$('#calc').append(contentToLoad);
number++;
});
}
But now I have a problem with making it work correctly, because it adds me the correct div + all divs which was previously added.
Let's just say that I have blank site and I want to add two divs, so I click twice on the button and it should add me two divs, but it adds after 1st click div with id = 1 and after 2nd click div with id = 2 + div with id=1, So in effect I have three divs after two clicks.
Where in code placed above I've made mistake ?
I have several div elements with incremental IDs (e.g. div0, div1, div2 (I know this is bad practice - I'm developing a dynamic CSV-to-HTML converter for Outlook calendar exports)) and I'd like to switch between them using jQuery linked to forward/back buttons . What I'm trying to do is as follows (in meaningless pseudo-code):
int pos = 0
forward.onclick
hide ("#div"+pos)
pos++
show ("#div"+pos)
back.onclick
if pos != 0
hide ("#div"+pos)
pos--
show ("#div"+pos)
Since I know next to nothing about jQuery, my questions are 1. What would the syntax be for implementing the above example (assuming I'm on the right track), and 2. Is there a way in jQuery to somehow check for an upper boundary so the counter doesn't increase above the number of divs?
If you want to know how many divs you have in jQuery, select them and take the length of your selection:
$('.div').length
You could even just use that selection to cycle through which divs to show:
var $divs = $('.div');
var upperLimit = $divs.length - 1;
var index = 0;
// on arrow click
$($divs[index]).hide();
index++ (or index--, depending on the arrow)
$($divs[index]).show();
int is not a data type in JavaScript. Use var. Declaration would be var pos = Number(0). To prevent exceeding the boundaries of number of divs, declare a variable with the number of divs you have, and inside your hide and show calls, use pos℅divLength instead of pos. Suppose you have total divs as 4, you will never exceed div3 this way. It will iterate from div0 to div3. Refer this to learn how to use show and hide methods.
Here's a demo.
var index = 0;
$('#div' + index).show();
$('#next').click(function () {
index++;
$('#back').prop('disabled', false);
if (index === fakeData.length - 1) {
$('#next').prop('disabled', true);
}
$('.items').hide();
$('#div' + index).show();
});
$('#back').click(function () {
index--;
$('#next').prop('disabled', false);
if (index === 0) {
$('#back').prop('disabled', true);
}
$('.items').hide();
$('#div' + index).show();
});
The above code will disable and enable the next and back buttons based on whether you are at the beginning or the end of your list of data. It hides all elements and then shows the specific one that should be shown.
I'm trying to add a simple "Read more" button to a page. I managed to prepare a working function that hides the maximum characters within an element. And to call the function I've prepared a button in the HTML with a "onclick" event to call the function.
Now a couple things happen that shouldn't. The button should reveal the hidden text but the opposite happens and everytime the button is clicked more characters are removed until I'm left with only the dots even though I have a var that limits the characters to 15. I have spent too much time trying to figure this out knowing this is probably basic jQuery. I apologize if that is the case I just hope someone can point out what I'm doing wrong here.
HTML:
<button class="content-toggle" onclick="textCollapse()">Read more</button>
jQuery:
function textCollapse() {
var limit = 15;
var chars = jQuery(".field-content p").text();
if (chars.length > limit) {
var visiblePart = jQuery("<span class='visiblepart'> "+ chars.substr(0, limit) +"</span>");
var dots = jQuery("<span class='dots'>... </span>");
jQuery(".field-content p").toggle()
.empty()
.append(visiblePart)
.append(dots)
}
};
I would save full text content into outer variable and keep it there. There is no need to requery text content every time a button is clicked. Also, it's better to have a variable that would store a state for the text - collapsed or not instead of comparing each time.
var fullText = jQuery(".field-content p").text();
var collapsed = false;
function textCollapse() {
var limit = 15;
if (collapsed) {
var visiblePart = jQuery("<span class='visiblepart'> " + fullText + "</span>");
jQuery(".field-content p")
.empty()
.append(visiblePart)
collapsed = false;
} else {
var visiblePart = jQuery("<span class='visiblepart'> " + fullText.substr(0, limit) + "</span>");
var dots = jQuery("<span class='dots'>... </span>");
jQuery(".field-content p")
.empty()
.append(visiblePart)
.append(dots)
collapsed = true;
}
}
Also, I don't think you need to call toggle() since all operations are performed synchronously and there's no need to hide p element before emptying and appending nodes.
I am trying to load DIV on button click inside another DIV and on another click it should create a new DIV inside the newly created DIV. Here is my fiddle:http://jsfiddle.net/LzCW5/4/ and my code:
HTML:
Generate
<div id='x0'>
0
</div>
JavaScript:
int level=1;
function nestDiv()
{
document.getElementById('x'+(level-1)).innerHTML="<div id='x"+level+"'>"+level+"</div>";
level++;
if(level==5)
//do somthing
}
I also want to perform some special operation when nesting level reaches 5. I am not so pro at JavaScript. So please tell me how can I achieve this?
In your code you only have to change int to var and call the function as a variable:
var level=1;
nestDiv = function()
{
document.getElementById('x'+(level-1)).innerHTML="<div id='x"+level+"'>"+level+"</div>";
level++;
}
You can see this working here
Here's how to append a div in jQuery:
var newDiv = $("<div id='x"+level+"'>"+level+"</div>");
$('#x'+(level-1)).append(newDiv);
This should replace your document.getElementById... line
My understanding as per your question:
When you click a button, add a div to another div.
Now when the user clicks another button, new div must be added in the previously created new div.
so let's break it down:
$("button").click(function() {
if($("#referenceDivId").children().length == 0) {
// if there are no children initially
$("#referenceDivId").append("<div>New div</div>");
} else if($("#referenceDivId").children().length == 5) {
// do your magic when children divs are 5
}
else {
// if it already had children
$("#referenceDivId").find("div:last").append("<div>New div</div>");
}
});
DEMO
I'm trying to append a div to the bottom of a another div, by clicking a button in javascript, but once the height of the outer container is reached, it no longer scrolls the list to the bottom, after an insert.
Please see the fiddle here
If you click the red add button until you get to about 13 items in the list, it seems something goes wrong with the scrollTop function, and it it no longer functions correctly (hovers around the same spot in).
I'm pretty lost on this, and have tried a bunch of different combinations of css settings for both the container and side div. Please help me.
I've reformatted your code to be more jQuery-esque. The main change, however, was to change the list.scrollTop() function so that it just scrolls to the bottom of list:
$(document).ready(function() {
var list = $("#q-d-list");
$(document).on('click', '#add', function() {
$('.active', list).removeClass("active");
var count = list.children().length + 1;
var active = $('<div />', {
'data-qid': count,
'class': 'mli active'
}).text('q' + count).appendTo(list);
list.scrollTop(list[0].scrollHeight);
});
});
Demo: http://jsfiddle.net/MrvcB/19/
Use
list.scrollTop(list.get(0).scrollHeight);
rather than
list.scrollTop($(".active").offset().top);
Try:
$(document).ready(function () {
var count = 2;
$("#add").live("click", function () {
var list= $("#q-d-list");
// remove the active class from the old item
var $clone = $(list.find("div:last-child").removeClass("active").clone());
count+=1;
var str_count = "q"+count.toString();
$clone.addClass("active").attr("data-qid",str_count).text(str_count);
list.append($clone);
list.scrollTop(list.get(0).scrollHeight);
});
});
http://jsfiddle.net/H4Kb3/