Check if a specific hidden div exists and if not create one - javascript

I want to check if a specific hidden div exists and if not create one.
I do:
function myFunction(somestring) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}
The problem is this seems to create a new hidden div every time the function is called on the same page.
the hidden div just seems scoped to the function, whereas I want it scoped to the page.
Any tips.
tips please
Thanks.

Use length property:-
function myFunction(somestring) {
var myHiddenDiv;
if($("#js_method").length == 0){
myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
$("body").append(myHiddenDiv);
}else{
myHiddenDiv = $("#js_method");
}
...
myHiddenDiv.append(somestring);
}

Why not just check by ID?
if (jQuery("#js_method").length == 0) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}

Related

Removing a created function in JavaScript

I have written this code by using some basics. I simply wanted to remove the image that I have created by using the function Generate() by a button. I have written the following code to remove the image generated. Please help me.
Please note that I have linked my button with the function Reset1(). Can someone give me the code to do the following please.
function Generate()
{
var image=document.createElement('img');
var div=document.getElementById('flex-box-gen');
image.src="https://thecatapi.com/api/images/get?format=src&type=gif&size=small"
div.appendChild(image);
}
function Reset1()
{
document.getElementById('Generate').remove();
}
You could either assign an id to your image element and use that to remove in your second function:
function generate() {
var image=document.createElement("img");
image.id = "image-01";
...
}
function reset() {
var image = document.getElementById("image-01");
var parent = image.parentNode;
parent.removeChild(image);
}
Or if there is nothing else in your containing div element you could just empty all elements from it:
function reset() {
document.getElementById("flex-box-gen").innerHTML = "";
}
getElementById will query a DOM element, not a javascript element.
What you can do, supposing you have only one img in your flex-box-gen is:
var imgs = document.querySelectorAll('#flex-box-gen img')
if(imgs.length > 0){
imgs[0].remove();
}
With a null-check in case the image was already removed
image.setAttribute('id',"Generate");
Add this line in generate function.

Javascript - Submit Text Field, Show Div, Hide All Others

I have a simple form (text field and submit button). I am trying to have the user submit a number, and the resulting number will display one div (from a set of divs).
I tried using this example as a base (when the user clicks a link, it shows a div, but hides others).
My test is below:
var divState = {};
function showhide(oFrm) {
var dividnum = oFrm.Inputed.value;
var prepar = "para";
var divid = prepar + theInput; /* should result in something like "para52" */
divState[divid] = (divState[divid]) ? false : true;
//close others
for (var div in divState){
if (divState[div] && div != divid){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
http://jsfiddle.net/LfzYc/431/
Note: I am NOT proficient in JavaScript at all, which is why I am having difficulty.
Also, I'd like to add a function ... if the number entered is not between 1-4, show a different div, maybe with the id paraEnd.
Please look at the jsFiddle based on your one. I hope I've done what you want. I changed the showhide function and your HTML (fixed div's IDs and added one more div#paraEnd). I'd suggest you refactoring your code.
You should use jQuery to have an easy way to manipulate the DOM.
Using jQuery I made an example for you, just change your JS and paste mine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// get the paragraphs
var paragraphs = $('.paragraph');
// form submit
$('#paragraphform').submit(function (e) {
// prevent the event to flow
e.preventDefault();
// get the input value
var value = $('#Inputed').val() - 1;
// reset all divs removing active css class
paragraphs.removeClass('active');
$('.error').removeClass('active');
// verify if the value doens't exist
if(value < 0 || value > paragraphs.length - 1) {
$('.error').addClass('active');
return;
}
// show the active div
paragraphs.eq(value).addClass('active');
});
})(jQuery);
</script>
Is that what you need?
If you not familiar with jQuery, this is the jquery Learn Center:
https://learn.jquery.com/
And this is a nice tutorial for beginners:
http://www.tutorialspoint.com/jquery/

How do i clear text out of a div using javascript

Okay here is what i have:
<script type="text/javascript">
var where = document.getElementById("info")
var texts = false;
function clear() {
where.innerHTML = "";
};
function dostuff(what) {
if(where.style.value === ""){
var comm = document.createTextNode(what);
where.appendChild(comm);
}else {
clear();
}
};
</script>
the id "info" is a div
this is basically a vertical navigation bar that shows tooltips in a div under the buttons when you hover over them.
So I want to first check if the div has no value then if it doesn't then it will append text into it, else it will clear the text but i also want it to append the text after it clears. I'm not sure how to do this and help would be appreciated. thanks
Since you want to clear the item anyways and put your new text in, why even bothering with the conditional? You could just as easily do:
function dostuff(what) {
where.innerHTML = what;
};
Working example

How to remove an element by id?

I just try a tutorial here on how to upload multiple form - http://www.maheshchari.com/multifile-upload/
Basically, it have a link to add a new input when it clicked. My question is, how to add another link to REMOVE the input?
Thanks for helping :)
You can remove an element that you know the ID of using:
function removeById(id) {
var element = document.getElementById(id);
// A bit of robustness helps...
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
}
please update you function add_file_field to
var file_counter = 0;
function add_file_field(){
file_counter++;
var container=document.getElementById('file_container');
var file_field=document.createElement('input');
file_field.name='images[]';
file_field.type='file';
file_field.id='file_'+file_counter;
container.appendChild(file_field);
var remove_field = document.createElement('a');
remove_field.href = "javascript:removeById('"+'file_'+file_counter+"');removeById('"+'remove_field_'+file_counter+"');";
remove_field.innerHTML = "Remove')";
remove_field.id = 'remove_field_'+file_counter;
var br_field=document.createElement('br');
container.appendChild(br_field);
}
this create a
and also add function removeById in you javascript so that when any one clicks on remove button then the file type field will remove. which is posted in previous post also
function removeById(id) {
var element = document.getElementById(id);
// A bit of robustness helps...
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
}
It's very simple,
document.getElementById("_id").parentNode.removeChild(document.getElementById("_id"));

Changing the class of a div when clicking on it?

How can I change a div class name when clicking on it? Eg:
<div class="first_name" onclick="changeClass();" id="first_name"></div>
I want to change it as follows, when a user clicks on the div
<div class="second_name" onclick="changeClass();"></div>
I wrote the JavaScript as:
<script language="javascript">
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name")
NAME.className="second_name"
}
</script>
It's working for the first instance only. That is on page load, if I click on it, the first_name gets changed into second_name. But clicking on it again, it won't revert the second_name to first_name.
You have to define the second class name. Currently, you have got a function which changes the class name to a hard-coded value, independent on the current class name. See also: MDN: if...else
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
var currentClass = NAME.className;
if (currentClass == "second_name") { // Check the current class name
NAME.className = "first_name"; // Set other class name
} else {
NAME.className = "second_name"; // Otherwise, use `second_name`
}
}
A quite late answer, but the reaction marked as answer can be shortened:
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
NAME.className = (NAME.className == "second_name") ? "first_name" : "second_name";
}
This is a shortened notation of the if-else structure. It checks if the className is equal to "second_name".
If it is, the currentClass variable will become "first_name", if it's not (meaning it's "first_name"),
it will become "second_name".
simple javascript function, put it in your application.js, or script tag :-
(jQuery should be included to run the following function)
function changeClass(){
$("#first_name").attr("class", "class-name-you-want-to-assign");
}
That's because there is no code to do so. Add a little check. I also added some semicolons. I wonder if your script would even work the first time.
<script language="javascript">
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
if (NAME.className==="second_name")
{
NAME.className="first_name";
}
else
{
NAME.className="second_name";
}
}
</script>
You have to use an if-statement to reverse it. Here's an example:
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name")
var currentClass = NAME.className;
if(currentClass == "second_name"){
NAME.className = "first_name";
} else {
NAME.className = "second_name";
}
}

Categories