How to create div with different class on button click? - javascript

I was creating a html that would create a div and copy the things in input to that div with a button click.
Like this:
HTML
<input type="text">
<button>Copy</button>
<p></p>
Script
$('button').click(function() {
var div = document.createElement('div');
$('p').append(div);
$('div').html($('input').val());
});
At it worked perfectly
And then i added class to it.
It looks like this:
$('button').click(function() {
var div = document.createElement('div');
div.className = "Someclass";
$('p').append(div);
$('div').html($('input').val());
});
It worked fine as well. But when i click the button it copies the text to all the div's Instead of a single one
How can i create a button that creates different div with different class and which copies text from <input> to the newly created div
I found on net that i can use the i++ thing in javascript for different class.
But that code is not working properly. Please tell me what is the mistake here.
My code looks like this:
$('button').click(function() {
var i = 0;
var div = document.createElement('div');
div.className = "Someclass" + i++;
$('p').append(div);
$('div').html($('input').val());
});

You can do it like this:
var clickCount = 0;
$('button').click(function() {
var html = $('input').val();
var classname = 'someclass' + clickCount++;
$('<div>').addClass(classname).html(html).appendTo('p');
});

take out i from click event
select new div with its corresponding class name .Someclass[i]
change your code like this:
var i = 0;
$('button').click(function() {
var div = document.createElement('div');
div.className = "Someclass" + i;
$('p').append(div);
$('.Someclass' + i).html($('input').val());
i++;
});

Rather use .addClass jquery method:
$( "div name" ).addClass( "yourClass" );

Its doing that because you have this line
$('div').html($('input').val());
You can change it to
$('p div').html($+'input').val());

You should give the precise class name like 'Someclass'+i with " i " the last index of the class you added.
$('button').click(function() {
var i = 0;
var div = document.createElement('div');
div.className = "Someclass" + i++;
$('p').append(div);
$('Someclass'+i).html($('input').val());
});
Your code looks like it will add only one div by click and that div will be given the value of input.

You are appending html to all div present.Do this add content to it before appending
var i=0;
$('button').click(function() {
var div = document.createElement('div');
div.className = "Someclass" + i++;
$(div).html($('input').val());
$('p').append($(div));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button>Copy</button>
<p></p>

Related

JavaScript/CSS Show respective div on click from grid

I have a working grid that show a cell for every title in the json:
async function loop_iteration(json, i, arr) {
arr.push(`<a onClick="show()" class="cell" id=${i}"><div >${json[i].title}</div> </a>`)
arr.push(`<div class="info" id=${i}>${json[i].title}<br><br><br><br><br>Game Size: ${json[i].size}<br><br>Last Update: ${json[i].date}</div>`)
}
I want to show on click of the class info.
The problem is that it gives always the same title(first), it's like is always the first cell to be clicked
I show the info div like this:
<script>
function showinfo() {
var node = document.querySelector('.cell.info')
var visibility = node.style.visibility;
node.style.visibility = visibility == "visible" ? 'hidden' : "visible"
}
</script>
while if i show the div using this:
function show(){
var divsToHide = document.getElementsByClassName("info");
for(var i = 0; i < divsToHide.length; i++)
{
divsToHide[i].style.visibility="visible";
}
//document.getElementsByClassName('info')['${i}'].style.visibility = 'visible';
}
happen something strange, the div showed is not the first but is like it show all the div
Thanks for any help.
I find out the problem.
It was the javascript, so i extract the id and then iterate the class with the id
function show(clicked_id){
clicked_id = parseFloat(clicked_id);
document.getElementsByClassName('info')[clicked_id].style.visibility = 'visible';
}

Change existing DIV from a CLASS to an ID

Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>

Change the onClick function to target the edit buttons

I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element

get dynamic text in text area on every click on div

I want to open the CKEDITOR on click-event of div, and want the div contents in that textarea of ckeditor
but somehow this is not working.
Thanks in advance, and sorry for my poor english
function createEditor() {
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
}
Remove createEditor() function and try it
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
Try this to add data to the textarea.
$("#editor1").val(newtext);
or use
$('#editor1').append(newtext);
This solution will rely more on jQuery. First, if you want this function to be triggered when ever a div is clicked, get rid of your function(), it's not necessary since your event will be triggered every time a div is clicked.
This should solve your problems:
$('div').click(function(e) {
$id1 = $(this).attr("id");
alert($id1);
$("#editor1").val(' '); //Are you sure you want to empty your textarea?
$newtext = $("#"+$id1).html();
alert($newtext);
$("#editor1").val($newtext); //Because when you append the newtext it won't append but replace the text it's already on this.
$("#contents").css("display","block");
});
Here's a fiddle with a similar example of using your function:
If you just want the text of the clicked div and you're using jQuery try
$("div").click( function() {
var newtext = $(this).text();
$("#editor1").text( newtext );
});

Creating divs with different id's

i have one question regarding creation of divs:
I have button, when user clicks on it, javascript (or jquery) needs to create a div. But when user clicks again, it should create another div, but with different id. So, every time user clicks should be created div with different id.
I partialy know how to create div, but i have no idea how to make divs with different id's.
var c = 0; // Counter
$('#add').on('click', function() {
c += 1;
$('#parent').append('<div id="child'+ c +'">'+ c +'</div>');
});
#child1{color:red;}
#child2{color:blue;}
#child3{color:orange;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">ADD</button>
<div id="parent"></div>
var divcount = 1;
$('button').click(function(){
$('<div/>', { id:'comment'+divcount++ })
});
Here's a random ID generator for you.
function createParanoidID() {
return 'id_' + Math.floor(Math.random() * 9e99).toString(36);
}
createParanoidID(); // id_1js7ogi93ixt6x29w9svozegzhal67opdt3l3cf1iqidvgazlyaeh1ha7a74bswsg
createParanoidID(); // id_1fleq6chguuyyljhy39x3g7mg661mg845oj8fphnxgvm0bdgz7t3w0q01jptogvls
createParanoidID(); // id_ajz1ft17ml4eyz08gd3thcvq3fx1ycr927i0h2zgyw8bzq9wurv1gdfogly8tbls
Using a variable as counter and the "attr" function to set the id attribute.
HTML
<button id="button">Create Div</button>
<div class="container"></div>
jQuery:
$('#button').on('click', function() {
var count = $('div.container div').length,
id = count + Math.floor(Math.random() * 100);
$('div.container').append('<div id="'+ id+'">ID of this div is: '+ id +' </div>');
});
DEMO
Here's the easy way to do this.
Firstly, you'll need a button:
​<button id="onClickOfThis​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ButtonAnewDivWithArandomIDwillBeInserted"></button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then the javascript:
$("#onClickOfThisButtonAnewDivWithArandomIDwillBeInserted").on('click', function() {
var myID = 'randomIDnumber_'+Math.random()+Math.random()+Math.random()+Math.random()+Math.random()+Math.random();
var MyNewElement = document.createElement('div');
MyNewElement.id = myID.replace(/\./g, '');
$(MyNewElement).appendTo('body');
});
Here's a FIDDLE
If you don't want to use global counter like in previous answers you can always get number of children and use that as relative value from which you will create another id.
Something like this (with jQuery):
function add_another_div() {
var wrap_div = document.getElementById("#id_of_div_who_contain_all_childrens");
var already_childs = $("#id_of_div_who_contain_all_childrens").children().length;
var div = document.createElement('div');
var divIdName = 'new_div-'+ (already_childs+1);
div.setAttribute('id', divIdName);
wrap_div.appendChild(div);
}
Of course, this requires for all of your children to have same parent (same wrapper). If that is not the case, and they are separated across multiple wrappers, then just use unique class name for all of them, and count them like that. I found this approach much better and easier instead of using global counters which I need to take care about.

Categories