show() method removes the html element from dom instead of displaying it - javascript

I have this code,
HTML and php
<?php for($i = 1; $i <= 5; $i++) { ?>
<div class="file-add-row" style="display:none;">Some content</div>
<?php } ?>
<div id="add-file-plus">Add File</div>
and the JS is
$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add-row:visible:last'));
}
});
Now, my problem is, when I click the add button for the first time, the first 'file-add-row' div is displayed. But when I click the add button the second time, nothing happens on the page. Instead, it just completely removes that div from the dom.
I am just a beginner in jquery, so there might be things I overlooked. Anyone got any idea about what's going on ?

When you do:
$('.file-add-row:visible:last')
Just after:
$('.file-add-row:hidden:first').removeAttr("style")
They both refer to the same object. And if you try to insert an object after itself, it will end up removing itself from the DOM.
Change the JS to:
$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
var last_visible = $('.file-add-row:visible:last')
$('.file-add-row:hidden:first').removeAttr("style").insertAfter(last_visible);
}
});
Demo (Click on 'Add File'):
https://jsfiddle.net/woxd2jbf/1/

Here's a version without jQuery just plain JavaScript, it will work with divs just as it does with button, ul, and li. The details are commented within the source.
Key Methods
cloneNode()
appendChild()
PLUNKER
SNIPPET
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--This <li> is a template to clone-->
<li class="row" style='display:none'>Some content</li>
<!--This is the empty list to be populated with clones-->
<ul id='list'>
</ul>
<!--This button will have an eventListener
that will execute a function when it is clicked-->
<button id="add">Add File</button>
<script>
/* Reference each element involved in process */
// The button
var add = document.getElementById('add');
// The list
var list = document.getElementById('list');
// The first li
var row = document.querySelector('.row:first-of-type');
/*
1. Button will listen for a `click`
2. Create a clone of the first li
3. Add clone as the last child of list
4. Set clone's display property to block
so it's visible
*/
add.addEventListener('click', function(e) {
var clone = row.cloneNode(true);
list.appendChild(clone);
clone.style.display = 'block';
}, false);
</script>
</body>
</html>

$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add- row:visible:last'));, due to this line the issue is happening. because it first removes the style attribute which makes it visible so $('.file-add- row:visible:last') is returning itself. refactor to store the visible el's reference like below:
$(function () {
$('#add-file-plus').live('click', function () {
if ($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
var $el = $('.file-add-row:visible:last');
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($el);
}
});
})

Related

How to update all values in an array? -JS/Jquery

I'm trying to update an array when clicking on the li tag. I've been testing, testing, and unable to come up with a solution.
I have two tabs: The "Create" tab opens a container that allows you to insert paragraphs, the "Home" tab opens another container containing a "Select paragraph" button.
Problem
It won't update the values of the array when I do it for the second time. I.e., if I switch between the tabs and go on select mode again to select/deselect, it will not update the new selection, instead I get the same selection from the first time.
I've created an example so you can look at it and if there is a better way to accomplish this (which I know there is) then be my guest. Link is below the next paragraph.
Instructions
In order to select a paragraph, first you need to add a paragraph which is created on the fly, then you switch to "Home" section, click on the "Select paragraph" button, this takes you to the "Create" section on select mode. To select/deselect, click on any paragraph. When you select a paragraph, it stores its position using jQuery - index() in the "storeClass" array. Once you're done selecting paragraphs then you exit the select mode by clicking "Ok" button and it switches to "Home" section, but let's say you want to create another paragraph then you click on "Create" tab, create the paragraph, switch to "Home" tab, go on select mode and select again and switch between tabs and you will see just the first selection you made on the first time.
Here is the same example: http://jsfiddle.net/7mbhnvas/8/
HTML
<ul class="tab">
<li><a class="paragraph-tab">Create</a></li>
<li><a class="select-tab">Home</a></li>
</ul>
<div class="wrap">
<div class="create-para-cont">
<h3>Create a paragraph</h3>
<ul class="para-results">
</ul>
<div class="para-tool">
<p><textarea class="textarea"></textarea></p>
<button type="button" class="create-para-button">Create paragraph</button>
<div>
<button type="button" class="select-ok-button">OK</button>
</div>
</div>
</div>
<div class="select-para-cont">
<h3>Select Mode</h3>
<p><button type="button" class="select-para-button">Select paragraph</button></p>
</div>
</div>
jQuery
$('ul.tab li a:first').addClass('tab-active');
$('.create-para-cont').addClass('cont-active');
$('.create-para-button').on('click', function(){
$('.create-para-cont').addClass('cont-active');
var parent = $('.para-results');
var child = $('<li></li>');
var p = $('<p></p>');
var textarea = $('.textarea').val();
if($('.create-para-cont').hasClass('cont-active')){
p.text(textarea);
child.append(p);
parent.append(child);
} else {
return false
}
});
var storeClass = [];
$('.select-para-button').on('click', function(){
$('.create-para-cont').addClass('cont-select');
if($('.para-results li').length >= 1){
$('.textarea, .create-para-button').hide();
$('.select-para-cont').hide();
$('.select-tab').removeClass('tab-active');
$('.create-para-cont').show();
$('.paragraph-tab').addClass('tab-active');
$('.select-ok-button').show();
for ( var i = 0; i < storeClass.length; i = i + 1 ) {
$('.para-results').each(function( index ) {
$( this ).find( "li:eq("+ storeClass[ i ] +")" ).addClass('p-selected');
});
}
}
});
$('ul.tab li').on('click','a', function(){
if($(this).hasClass('paragraph-tab')){
$('.para-results').children('li').removeClass('p-selected');
$('.select-para-cont').hide();
$('.select-tab').removeClass('tab-active');
$('.create-para-cont').show();
$('.paragraph-tab').addClass('tab-active');
} else {
$('.create-para-cont').removeClass('cont-active');
$('.create-para-cont').hide();
$('.paragraph-tab').removeClass('tab-active');
$('.select-para-cont').show();
$('.select-tab').addClass('tab-active');
}
});
$('ul.para-results').on('click','li', function(){
if($('.create-para-cont').hasClass('cont-select')){
$(this).toggleClass('p-selected');
var selected = $('.p-selected ');
var pSelected = selected.parent().children().index(this);
storeClass.push( pSelected );
} else {
return false;
}
});
$('.select-ok-button').on('click', function(){
if($('.create-para-cont').hasClass('cont-select')){
$('.create-para-cont').removeClass('cont-select');
$('.create-para-cont').removeClass('cont-active');
$('.create-para-cont').hide();
$('.paragraph-tab').removeClass('tab-active');
$('.select-para-cont').show();
$('.select-tab').addClass('tab-active');
}
});
I would reset storeClass to a blank array when the 'OK' button is clicked, and then re-push all the correct values into it in that same click handler:
$('.select-ok-button').on('click', function(){
if($('.create-para-cont').hasClass('cont-select')) {
storeClass = []; // make it blank
$('.p-selected').each(function() {
storeClass.push($(this).index()); // push each one into the array
});
....
}
});
Then your click handler of ul.para-results would look like this:
$('ul.para-results').on('click','li', function(){
if($('.create-para-cont').hasClass('cont-select')){
$(this).toggleClass('p-selected');
} else {
return false;
}
});
Here's an updated Fiddle

Getting inner HTML from different ids

I'm just now starting to try to learn Javascript, so bear with me. I'm trying to get information from a list on one part of my page to a new section with three places at the click of a button.
Each item in the list has its own button, and I need my script to know which place to put the list item based on the number of times the button has been clicked (which should coincide with how many list items have already been added to the list).
I've tried created a script to increase i and take the id of the paragraph into a function, but I can't seem to make it work. I'm hoping that by "counting" the number of times the button has been clicked, it will put each new list item that has been added in the next place in the new section.
I'm not sure how to make the counting part work, though, and it has just occurred to me that maybe the first part of my function constantly remains at zero.
I would really appreciate any help that I can get with this.
Thanks in advance!
Here's my code:
<script>
function increase(place) {
var i = 0;
addToDilly(i, place);
i++;
}
function addToDilly(num, place) {
if num = 0 {
document.getElementById("firstStop").innerHTML = document.getElementById(place).innerHTML;
}
if num = 1 {
document.getElementById("secondStop").innerHTML = document.getElementById(place).innerHTML;
}
if num = 2 {
document.getElementById("thirdStop").innerHTML = document.getElementById(place).innerHTML;
}
}
</script>
<p id="firstStop">This is a paragraph.</p>
<p id="secondStop">This is another paragraph.</p>
<p id="thirdStop">This is another paragraph.</p>
<hr/>
<p id="1">Royal Oak <button onclick="increase(1)">Add To Dilly</button></p>
<p id="2">Ferndale <button onclick="increase(2)">Add To Dilly</button></p>
<p id="3">Chesterfield <button onclick="increase(3)">Add To Dilly</button></p>
Try this script:
<script>
var i = 0;
function increase(place) {
console.log(place);
addToDilly(i, place);
i++;
}
function addToDilly(num, place) {
if (num == 0) {
document.getElementById("firstStop").innerHTML = document.getElementById(place).innerHTML;
}
if (num == 1) {
document.getElementById("secondStop").innerHTML = document.getElementById(place).innerHTML;
}
if (num == 2) {
document.getElementById("thirdStop").innerHTML = document.getElementById(place).innerHTML;
}
}
</script>
Here's the running example
I would suggest a complete re-write. If your aim is to update a list of items, just update a list of items (literally) :)
Note: You originally tagged your question as jQuery, so this initial answer is in jQuery.
The text you wish to add needs to been in an element related to the button, but not containing the button itself. For this example I placed them before the buttons.
e.g. http://jsfiddle.net/TrueBlueAussie/t13h54bu/3/
$('button').click(function () {
var $button = $(this);
var text = $button.prev('p').html();
var $target = $('#list');
$target.append($('<li>').html(text));
});
and simpler HTML:
<ul id="list"></ul>
<hr/>
<p>Royal Oak</p>
<button>Add To Dilly</button>
<p>Ferndale</p>
<button>Add To Dilly</button>
<p>Chesterfield</p>
<button>Add To Dilly</button>
Then if you want to limit the items to 3 add this:
if ($target.children().length < 3) {
$target.append($('<li>').html(text));
}
http://jsfiddle.net/TrueBlueAussie/t13h54bu/4/

When one is clicked, disable the other

So I have a mini slide menu in my website there is a menu you can choose what you want to read. There are points to click, when u clicked it the point get a red background.
But there is a problem.
When i click one point and then an other point the first clicked point have to lose his background.
Here is my HTML:
<div id="slide_button" onClick="clicked(this);"><dir class="button_1"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_2"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_3"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_4"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_5"></dir></div>
Here is my JS:
function clicked(slide_button) {
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
HERE IS AN EXAMPLE ON FIDDLE.
My "QUESTION IS" what i have to do to solve that?
What should I pay attention?
First you need to fix your HTML becaue your id values aren't unique. In fact, you don't even need id values, so you should use "slide_button" as a class. You can then use it to select all the buttons:
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
The CSS needs to be changed now so "slide_button" is a class selector, instead of an id selector:
.slide_button {
display: inline-block;
}
As for clearing the background, clear all of them before coloring the selected one red:
function clicked(slide_button) {
var buttons = document.getElementsByClassName('slide_button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].getElementsByTagName('dir')[0].style.backgroundColor = '';
}
slide_button.getElementsByTagName('dir')[0].style.backgroundColor = 'red';
}
jsfiddle
This uses just JavaScript with no JQuery, but if you are using JQuery, you might as well use it here. The code is a lot shorter and easier to follow.
Here's a JQuery version:
$(function() {
$('.slide_button').click(function() {
var $button = $(this);
$button.children(':first').css({ backgroundColor: 'red' });
$button.siblings().children(':first').css({ backgroundColor: '' });
});
});
Note: This registers a click-handler, so you can get rid of the "onclick" attirbutes.
jsfiddle
You have to select all other points and set their background to none.
Or remeber which point is selected and on select another just remove background on last and remeber current point, then set its background to red.
See fiddle: http://fiddle.jshell.net/399Dm/5/
At first id should be unique per element.
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
Second, you should store reference of clicked element if you want later remove background color, and instead of inline event handlers or binding all elements would be better if you use event delegation.
Demonstration
(function () {
"use strict";
// getting parent node of divs, due to bind click event. then
var ele = document.querySelector(".slide_button").parentNode,
prev = null; // store previous clicked element
ele.addEventListener("click", clickHandler); // event handler.
function clickHandler(e) {
var t = e.target; // get target of clicked element
// filter by target node name and class. edit: removed class checking
if (t.nodeName.toLowerCase() === "dir") {
// checking value of prev !== null and it's not same element.
if (prev && prev !== t) {
prev.style.backgroundColor = "";
}
prev = t; // store clicked element
t.style.backgroundColor = "red";
}
}
}());
I have fixed the fiddle so that it works hopefully as you plan.
http://jsfiddle.net/399Dm/8/ There you go!
var forEach = function(ctn, callback){
return Array.prototype.forEach.call(ctn, callback);
}
function clear(element, index, array) {
element.getElementsByTagName("dir")[0].style.backgroundColor="";
}
function clicked(slide_button) {
forEach(document.getElementsByClassName("slide_button"), clear);
//.style.backgroundColor="";
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
I had a slightly different method than #atlavis but a similar result.
http://fiddle.jshell.net/2AGJQ/
JSFIDDLE DEMO
jQuery
$('.slide_button').click(function(){
$('.slide_button dir').css("background-color", "inherit");
$(this).find('dir').css("background-color", "red");
});
HTML - Your markup is invalid because you have duplicate ids. Make them classes as below instead.
<div class="slide_button" >
<dir class="button_1"></dir>
</div>
<div class="slide_button">
<dir class="button_2"></dir>
</div>
<div class="slide_button">
<dir class="button_3"></dir>
</div>
<div class="slide_button">
<dir class="button_4"></dir>
</div>
<div class="slide_button">
<dir class="button_5"></dir>
</div>
CSS change
.slide_button {
display: inline-block;
}
If you can look at the following jsfiddle, I used jQuery to get what you want.

How do I keep current item in view in an overflown div?

I have a div with a fixed height of 400px and a long list of items inside. Clicking on prev/next links will move you throught the list. The problem is, after a while, the current item will be out of view. How can I move the scrollbar with the current item?
I've made a demo, have a look: http://jsbin.com/idunaf
<!DOCTYPE html>
<html>
<head>
<style>
#listContainer{height:400px;width:300px;overflow:auto;background-color:#eee;}
.selectedItem{background-color:white;color:red;}
</style>
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
for(var a=[],i=0;i<100;++i){
a[i]=i;
}
currentItem = 0;
$(document).ready(function() {
var items = [];
$.each(a, function(i,x){
items.push('<li id="item_'+x+'">item #'+x+'</li>');
});
$('#list').append(items.join(''));
$('#next').click(function() { updateList(); currentItem += 1; });
$('#prev').click(function() { updateList(); currentItem -= 1; });
});
function updateList(){
$('#listContainer').find('.selectedItem').removeClass('selectedItem');
$('#item_'+currentItem).addClass('selectedItem');
}
</script>
</head>
<body>
<< PREV ITEM | NEXT ITEM >>
<div id="listContainer">
<ul id="list"></ul>
</div>
</body>
</html>
You should be able to use the (non-jQuery) DOM method element.scrollIntoView():
$('#item_'+currentItem).addClass('selectedItem')[0].scrollIntoView(true);
// or
$('#item_'+currentItem)[0].scrollIntoView(true);
// or
document.getElementById('item_'+currentItem).scrollIntoView(true);
The [0] is just to get a reference to the actual DOM element from the jQuery object - given you're selecting by id I assume there can only ever be one element matching the selector. Of course with most jQuery methods setup to allow chaining you can do this on the end of the existing .addClass() rather than selecting the element again.
(Have a look at the .scrollIntoView() doco to decide whether to pass true or false (or nothing) to the method.)

How to Reduce Size of This jQuery Script and Make it More Flexible?

I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>

Categories