add div to parent div without duplication - javascript

i have a user div, containing a list of users and onclick of any user i want a div with 3 child divs to be appended to another parent div.but when try running my code, 3 appended divs are created when two users are clicked and 5 appended divs are created when 3 users are clicked please any help will be appreciated. below is my code
<htmL>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<style>
.clear{
clear:both:
}
.mainwrapper{
width:700px;
border-style:solid;
bottom:5000px;
z-index:2;
margin-left:20px;
margin-top:150px;
//display:none;
}
.wrapper{
height:300px;
width:300px;
border-style:solid;
float:left;
}
.wrapper1{
height:90px;
width:280px;
border-style:solid;
margin:5px;
}
.wrapper11{
height:50px;
width:80px;
border-style:solid;
float:left;
}
.wrapper12{
height:50px;
width:190px;
border-style:solid;
}
.wrapper2{
height:90px;
width:280px;
border-style:solid;
margin:5px;
}
.wrapper21{
height:50px;
width:80px;
border-style:solid;
float:left;
}
.wrapper22{
height:50px;
width:190px;
border-style:solid;
}
.wrapper3{
height:90px;
width:280px;
border-style:solid;
margin:5px;
}
</style>
<body>
<div class="user">
<p>first</p>
<p>second</p>
<p>thid</p>
</div>
<!----parent container---->
<div class="mainwrapper">
</div>
</body>
<script>
$(".user").click(function () {
//alert('oko');
create();
})
function create(){
$('<div/>',{ class : 'wrapper'}).appendTo(".mainwrapper");
$('<div/>',{ class : 'wrapper1'}).appendTo(".wrapper");
$('<div/>',{ class : 'clear'}).appendTo(".wrapper1");
$('<div/>',{ class : 'wrapper2'}).appendTo(".wrapper");
$('<div/>',{ class : 'clear'}).appendTo(".wrapper2");
$('<div/>',{ class : 'wrapper3'}).appendTo(".wrapper");
$(".wrapper3").append('<form action="chatprocess.php?id="+"e"+" method="POST">');
$(".wrapper3 form").append('<input type="text" placeholder="Name" name="a" id="rname"/>');
$(".wrapper3 form").append('<br><input type="submit" name="submit" value="Send" />');
$(".wrapper3 form").attr('action', 'chatprocess.php?send='+send+'&&rec='+user+'&&cat='+cat);
return user
}
</script>
</html>

You shoud add some distinct tag to the wrapper class name that is added to the mainwrapper when you create the new divs so as to associate it with the specific user that was clicked.
To do that pass the tag ("user1" for example) in the create function.
Then name wrapper class as wrapper_user1 instead of just wrapper.
What happens with your code is that when you click on the 2nd and 3rd user, when you append to "wrapper" it is appending to the new wrapper you added, but also to the ones you created before by clicking user 1 and 2.
The same happens with wrapper3. I suggest you tag all your wrappers with the corresponding user in case you add more functionality.
If you want to keep the tagging only at the first level of wrappers you will need to change how you select the different elements by prepending the corresponding tagged wrapper in the jQuery selector.
Note: Also check your code. js has some syntax errors and undefined variables. Css also has syntax errors.
$(".user a").click(function() {
//alert('oko');
var tag = $(this).attr('data-tag');
create(tag);
});
function create(tag) {
var newClass = 'wrapper_' + tag;
//Declared for snippet to work
var send ="";
var user="";
var cat="";
//----------
$('<div/>', {
class: newClass
}).appendTo(".mainwrapper");
$('<div/>', {
class: 'wrapper1 wrapper1_' + tag
}).appendTo("." + newClass);
$('<div/>', {
class: 'clear'
}).appendTo(".wrapper1_" + tag);
$('<div/>', {
class: 'wrapper2 wrapper2_' + tag
}).appendTo("." + newClass);
$('<div/>', {
class: 'clear'
}).appendTo(".wrapper2_" + tag);
$('<div/>', {
class: 'wrapper3 wrapper3_' + tag
}).appendTo("." + newClass);
$(".wrapper3_" + tag).append('<form action="chatprocess.php?id="+"e"+" method="POST">');
$(".wrapper3_" + tag + " form").append('<input type="text" placeholder="Name" name="a" id="rname"/>');
$(".wrapper3_" + tag + " form").append('<br><input type="submit" name="submit" value="Send" />');
$(".wrapper3_" + tag + " form").attr('action', 'chatprocess.php?send=' + send + '&&rec=' + user + '&&cat=' + cat);
return user;
}
.clear {
clear: both;
}
.mainwrapper {
width: 700px;
border-style: solid;
bottom: 5000px;
z-index: 2;
margin-left: 20px;
margin-top: 150px;
//display:none;
}
.wrapper {
height: 300px;
width: 300px;
border-style: solid;
float: left;
}
.wrapper1 {
height: 90px;
width: 280px;
border-style: solid;
margin: 5px;
}
.wrapper11 {
height: 50px;
width: 80px;
border-style: solid;
float: left;
}
.wrapper12 {
height: 50px;
width: 190px;
border-style: solid;
}
.wrapper2 {
height: 90px;
width: 280px;
border-style: solid;
margin: 5px;
}
.wrapper21 {
height: 50px;
width: 80px;
border-style: solid;
float: left;
}
.wrapper22 {
height: 50px;
width: 190px;
border-style: solid;
}
.wrapper3 {
height: 90px;
width: 280px;
border-style: solid;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="user">
<p><a data-tag="user1" href="#">first</a></p>
<p><a data-tag="user2" href="#">second</a></p>
<p><a data-tag="user3" href="#">thid</a></p>
</div>
<!----parent container---->
<div class="mainwrapper"></div>

Have a DIV set in which you want to append//add 3 DIV, something like this:
<div id='parentDiv'>
<!-- place where 3 DIVs will be inserted -->
</div>
Somewhere you will have three texts for a click event to happen, add an onClick event to all the texts:
<div>
<a class = 'clickMe' onclick="myFunction()">one</a></div></br>
<a class = 'clickMe'onclick="myFunction()">two</a></br>
<a class = 'clickMe'onclick="myFunction()">three</a></br>
</div>
In a script tag define a string with has 3 DIVs inside a parent DIV, something like this:
var divWith3ChildDiv = '<div><div style="background-color:blue;">this is 1st added DIV</div><div style="background-color:red;">2nd Added DIV</div><div style="background-color:pink;">3rd added DIV</div></div>';//a parent DIV with 3 DIVs inside it
And then you can have your onClick event function which will use innerHTML method to add the string defined above as HTML to the 'parentDiv'
var getElements = document.getElementsByClassName('clickMe');
var myDiv = document.getElementById('parentDiv');
function myFunction(){
myDiv.innerHTML = divWith3ChildDiv;
}

Related

How can I have text resize based on the width of the preceding div element using CSS?

I have a label I'm attempting to generate. It has the following structure.
.name-box { width: 400px; background-color: #efefef; border: 1px solid #000; overflow: hidden; white-space: nowrap; }
.last-name { font-size: 26px; display:inline; overflow: hidden;}
.first-name { display:inline; overflow: hidden;}
<div class="name-box">
<div class="last-name">McDonald-OrAReallySuperDuperLongLastName</div>
<div class="first-name">David</div>
</div>
What I'm wanting to do is change the text size of the first name, based on the length of the last name. If the name is "Venckus-Stringfellow" and I only have a little bit of space left I'd like the text size of the first name to be around 7px. But if the last name is "Le", then I'd want the first name to have a text size of 26px -- granted that having a text size of 26px still allows the first name to fit on the 600px that my div has to fill the label. How can I do this with HTML/CSS (if I MUST use Javascript then that's fine, was trying to avoid it though) ?
Javascript that uses the length of the last name in a mathematical equation to set the first names size. This is a very simple example and you'd need to change it if you wanted it to be exponential and you should probably set high and low bounds that it can't go below.
var lastNameText = document.querySelector('.last-name').textContent;
var firstName = document.querySelector('.first-name');
firstName.style.fontSize = (120 / lastNameText.length) + "px";
.name-box { width: 600px; }
.last-name { font-size: 26px; }
.first-name: { font-size: 26px; }
<div class="name-box">
<div class="last-name">McDonald</div>
<div class="first-name">David</div>
</div>
You're going to need javascript here, unfortunately. You can get close using viewport percentages, but that applies to the whole viewport. And it would only be for one container, not a preceding container. What you are going to need to do is create an algorithm that updates the font sizes, and run it everytime you load HTML/text into those div's.
Something like this should get you started:
function loadNames(var firstName, var lastName) {
//GET THE LENGTH OF THE LASTNAME STRING
var len = lastName.length;
var factor = .7; //CUSTOMIZE THIS TO DO YOUR SIZING BASED ON THE FONT
var fontSize = Math.ceil(factor * len); //GET THE NEW FONT SIZE, BASED ON THE LENGTH AND FACTOR, AND ROUNDED UP
//SET THE TEXT OF THE NAMES
$('firstName').Text(firstName);
$('lastName').Text(lastName);
//SET THE FONT SIZES
$('firstName').css({ 'font-size': fontSize + 'px;' });
$('lastName').css({ 'font-size': fontSize + 'px;' });
}
CSS solution unfortunately is not possible. It's not possible to select partial text inputs, and there's some calculation required that cannot be done with CSS at this point, in this age.
But javascript.. Were you looking for something like this OP?
$(document).on("ready", function(){
var ratio = 20;
$(".name").keydown(function(){
var input_length = $(this).val().length / ratio;
var new_size = (2 - input_length < 1 ? 1 : 2 - input_length);
$(this).css("font-size", new_size+"em");
});
});
input {
width: 40em;
margin: 0 auto;
display: block;
padding: 15px;
}
.main-wrapper {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-wrapper">
<input class="name" type="text" placeholder="Enter name" />
</div>
This is another approach how You could achieve the result. Maybe it's possible to do not use table at all but each div should use display:inline-block; property.
$scalingL = $('.last-name').width();
$scalingF = $('.first-name').width();
$('.first-name').css('font-size',($scalingL / $scalingF * 26));
.name-box { width: 600px; background-color: #efefef; border: 1px solid #000; overflow: hidden; white-space: nowrap; }
.last-name { font-size: 26px; overflow: hidden; display:inline-block;}
.first-name { font-size: 26px; display:inline-block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="name-box">
<table>
<tr>
<td>
<div class="last-name">McDonald-OrAReallySuperDuperLongLastName</div>
</td>
</tr>
</tr>
<td>
<div class="first-name">Something</div>
</td>
</tr>
</table>
</div>
Try this:
<style type="text/css">
.name-box{
width:auto;
overflow:auto;
}
#first-name{
display:inline-block;
width:auto;
clear:both;
float:left;
font-size:1px;
}
#last-name {
display:inline-block;
width:auto;
clear:both;
float:left;
font-size:26px;
}
</style>
<div class="name-box">
<div id="last-name">McDonalds</div>
<div id="first-name">David</div>
</div>
<script type="text/javascript">
var ln = document.getElementById("last-name");
var fn = document.getElementById("first-name");
for ( i = 1; ln.offsetWidth>fn.offsetWidth; i+=.5)
{
fn.style.fontSize=(i)+"px";
}
</script>
<style type="text/css">
.name-box{
width:auto;
overflow:auto;
}
#first-name{
display:inline-block;
width:auto;
clear:both;
float:left;
font-size:1px;
}
#last-name {
display:inline-block;
width:auto;
clear:both;
float:left;
font-size:26px;
}
</style>
<div class="name-box">
<div id="last-name">McDonalds</div>
<div id="first-name">David</div>
</div>
<script type="text/javascript">
var ln = document.getElementById("last-name");
var fn = document.getElementById("first-name");
for ( i = 1; ln.offsetWidth>fn.offsetWidth; i+=.5)
{
fn.style.fontSize=(i)+"px";
}
</script>

Creating a tag box

I'm making a tag box similar to that of StackOverflow. I see that this question has already been asked here (How to make a "tags box" using jQuery (with text input field + tags separated by comma)) but I'm having a question with regards to the Javascript.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tag-container' id = "tag-container">
<span class='dashfolio-tag'>Tag1</span>
<span class='dashfolio-tag'>Tag2</span>
<span class='dashfolio-tag'>Tag3</span>
</div>
<input type="text" value="" placeholder="Add a tag" id = "add-tag-input" />
CSS:
.tag-container {
max-width: 300px; /* helps wrap the tags in a specific width */
}
.dashfolio-tag {
cursor:pointer;
background-color: blue;
padding: 5px 10px 5px 10px;
display: inline-block;
margin-top: 3px; /*incase tags go in next line, will space */
color:#fff;
background:#789;
padding-right: 20px; /* adds space inside the tags for the 'x' button */
}
.dashfolio-tag:hover{
opacity:0.7;
}
.dashfolio-tag:after {
position:absolute;
content:"×";
padding:2px 2px;
margin-left:2px;
font-size:11px;
}
#add-tag-input {
background:#eee;
border:0;
margin:6px 6px 6px 0px ; /* t r b l */
padding:5px;
width:auto;
}
JS:
$(document).ready(function(){
$(function(){
$("#add-tag-input").on({
focusout : function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
this.value = "";
},
keyup : function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)
if(/(188|13)/.test(ev.which)) $(this).focusout();
}
});
$('.tag-container').on('click', 'span', function() {
if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
});
});
});
My question is pretty simple, how do I add the new input as a span with class dashfolio-tag inside the #tag-container? I dabbled with the insertBefore property trying to add it to the right node, but to no avail. Thanks in advance guys!
Change this line of code,
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
to
if(txt) {
$("<span/>", {
text:txt.toLowerCase(),
appendTo:"#tag-container",
class:"dashfolio-tag"
});
}
See the demo: https://jsfiddle.net/2gvdsvos/4/
To fix the margins in between tags,
Update HTML to,
<div>
<div class="tag-container" id="tag-container">
<span class='dashfolio-tag'>tag1</span>
<span class='dashfolio-tag'>tag2</span>
<span class='dashfolio-tag'>tag3</span>
</div>
</div>
<div>
<input type="text" value="" placeholder="Add a tag" id="add-tag-input" />
</div>
And add this to CSS,
.tag-container:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.dashfolio-tag {
...
margin-right: 4px;
float: left;
}
Hope this helps! ;)
https://jsfiddle.net/2gvdsvos/5/

Prevent auto scroll when prepend something

I have this code.
<div class="mes-all">
<div class="mes" id="1">test1</div>
</div>
<button id="add">Send</button>
And on every submit some .mes divs prepending to .mes-all div.But I want it not scroll auto,I want it maintain position same as before prepending divs above.
I have looked for solution in even this site,but couldn't find.
I can't control height() or scrollTop(), I don't know this functions very well,that's why I can't figure out the problem.
I have jsfiddle https://jsfiddle.net/83xq3b3L/
js:
var $elem = $('#list');
var height = $elem.height();
$("#add").on("click",function(){
var id=parseInt($(".mes:first").attr("id"))+1;
$(".mes-all").prepend('<div class="mes" id="'+id+'">test'+id+'</div>');
height+=30;
$(".mes-all").animate({scrollTop: height+"px"});
});
HTML:
<div id = "list" class="mes-all">
<div class="mes" id="1">test1</div>
</div>
<button id="add">Send</button>
One approach is to get the scrollHiehgt of the parent div and then scrollTop to that height.
So you code might look like this:
$("#add").on("click", function() {
var id = parseInt($(".mes:first").attr("id")) + 1;
$(".mes-all").prepend('<div class="mes" id="' + id + '">test' + id + '</div>');
var divHiehgt = $('.mes-all')[0].scrollHeight;
$('.mes-all').scrollTop(divHiehgt);
});
.mes-all {
overflow: auto;
height: 300px;
border: 1px solid;
}
.mes {
height: 30px;
padding: 5px;
border: 1px solid red;
text-align: center;
vertical-align: middle;
padding-top: 15px;
background: #ebebeb;
}
button {
width: 100%;
height: 50px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mes-all">
<div class="mes" id="1">test1</div>
</div>
<button id="add">Send</button>
Or jsFiddle:
https://jsfiddle.net/j8jaz10k/1/

I am trying to display a div on click of a checkbox

I need to display an image and some info about the item when a checkbox is clicked. For some reason nothing is happening and I have been tweaking this for a while with no response whatsoever.
Here is my javascript:
<script type = "text/javascript">
function displayOnChecked(var checkboxID, var id) {
if(document.getElementById(checkboxID)) {
document.getElementById(id).style.display = "block";
} else {
document.getElementById(id).style.display = "none";
}
}
</script>
In the stylesheet I have it on display: none;
Here is one of my invocations:
<input type="checkbox" name="purchasedItem" id = "item" onclick="displayOnChecked('item', 'itemInfo');">
No need for the var keyword in the arguments list of displayOnChecked, just have the variable names alone.
If you look in your console, you should be getting an error: Uncaught SyntaxError: Unexpected token var
You don't intialize variables as function arguments:
function displayOnChecked(var checkboxID, var id)
should be
unction displayOnChecked(checkboxID, id)
You can achieve this, just using the CSS pseudo-element :checked:
.checkmeout {
display: none;
position: absolute;
top: 12px;
left: 150px;
width: 400px;
height: 100px;
padding: 12px;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
}
.checkmeout img {
display: block;
width: 200px;
height: 50px;
background-color: rgb(0,0,255);
}
.checkme:checked ~ .checkmeout {
display:block;
}
<form>
<input type="checkbox" name="checkme" class="checkme" /> Check Me
<div class="checkmeout">
<img src="" alt="Check Me Out Image" />
<p>Check Me Out Text Description</p>
</div>
</form>

How to add Div inside Div Dynamically

I have a Div in which I want to add another small Div's Dynamically. But small Div's strictly needs to be inside the main Div. I have added one small Div inside. But how to add all the 15 div's inside the main Div dynamically I'm not getting. Also the size of small Div's are fixed, if they are more in numbers say 20, then Main Div should have horizontal scroll bar.
Here is the HTML used:
<div id="tables" style="width:740px; height:50px; border:1px solid;margin-left:180px;">
<div id ="1" style="border:1px solid; height:44px; width:50px; margin-left:2px; margin-top:2px; margin-bottom:2px;">1</div>
</div>
And here is my fiddle link: Fiddle.
You need to loop as many times as required, create the elements and then append them to #tables. Something like this:
var $tables = $('#tables');
for (var i = 1; i <= 15; i++) {
$('<div />', { class: 'inner', text: i }).appendTo($tables);
};
Example fiddle
You can add the id property back in if needed, but I would advise against incremental id attributes as they only lead to a maintenance headache. Also, I changed the styling to use actual CSS classes for a better separation of concerns.
You can use the following code in jQuery to append a div :
smallDivWidth = (740 / 15);
for (var i = 1; i <= 15; i++) {
$('#tables').append('<div style="border:1px solid; height:44px;float:left; margin- left:2px; margin-top:2px; margin-bottom:2px;">1</div>');
$('#tables').children().css('width',(smallDivWidth-4)+'px');
};
Just as an example, see this here :
$("#btnDynamicDiv").click(function() {
var smallDivWidth = (740 / 15);
for (var i = 1; i <= 15; i++) {
$('#tables').append('<div style="border:1px solid; height:44px;float:left; margin- left:2px; margin-top:2px; margin-bottom:2px;">1</div>');
$('#tables').children().css('width',(smallDivWidth-4)+'px');
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="tables" style="width:740px; height:50px; border:1px solid;margin-left:180px;">
<div id ="1" style="border:1px solid; height:44px; width:50px; margin-left:2px; margin-top:2px; margin-bottom:2px;">1</div>
</div>
<input type="button" id="btnDynamicDiv" value ="Add div dynamically"></input>
Try like this (JSFiddle demo)
HTML:
<div id="tables">
<div class="inner" id="innder-1">1</div>
</div>
<div class="inner inner-template"></div>
<br>
<button id="add-btn">Add inner</button>
CSS:
#tables {
width:200px;
height:50px;
border:1px solid;
white-space: nowrap;
overflow-x: auto;
}
.inner {
border:1px solid;
height:44px;
width:50px;
margin-left:2px;
margin-top:2px;
margin-bottom:2px;
display: inline-block;
vertical-align: top;
white-space: howrap;
}
.inner-template {
display: none;
}
JS:
var $template = $('.inner-template');
$('#add-btn').on('click', function() {
var currentID = $('#tables .inner').length + 1;
var $inner = $template
.clone()
.removeClass('inner-template')
.attr('id', 'inner-' + currentID)
.text(currentID)
.appendTo('#tables');
});

Categories

Resources