Create multiple buttons in JavaScript - javascript

I have checked for syntax errors and it does seems like everything is okay, it just does not do anything when loading the body of the page. I know I have linked the script correctly to the html file, because I've already implemented a JS Clock which displays itself in the page as you can see in the pen. Is there anything wrong with my code? Why aren't my 10 buttons displaying? I fear Bootstrap may be preventing me from getting my buttons show up.
My purpose is to create 10 buttons, so that I don't have to write the same code 10 times.
The Codepen is just to check out my code, I work on Atom usually. This is my Codepen!
<div class="container-fluid" id="buttons">
</div>
function createButtons() {
for(i = 0; i < 11; i++) {
var button = document.createElement("<button type=\"button\" class=\"btn btn-outline-success\">Chapter[i]</button>");
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}
}
document.body.addEventListener("load", createButtons(), false);

The function createElement accept a tag name as argument.
var Chapter = [0,1,2,3,4,5,6,7,8,9,10];
for(i = 0; i < 11; i++) {
var button = document.createElement("button");
button.innerHTML = Chapter[i];
button.className = "btn btn-outline-success";
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}

Related

Javascript click on specific element always uses wrong/other element id

I have several html pages and each one has a varying number of buttons that appear based on the page's content.
In just Javascript (since I don't use jquery), I am trying to have the same few lines of code apply to the respective button that was clicked, with the exception that the id tag has to be 'concatenated' into a variable based on the respective button that was clicked.
I saw other solutions on here that cycled through the elements of the class (in this case the "zoom_buttonClass"). However, when I attempt this, regardless of number of buttons on the page or which button was clicked, it is always the LAST button in the list that seems to be the one seen as clicked.
I need to always check if buttons are clicked, but how do I apply the actions based on the ACTUAL button that was clicked?
My HTML and JS code snippets are below:
Thanks in advance.
HTML code:
<div class="modalClass" id="myModalID">
<span class="closeModalClass" aria-label="Close Photo Enlargement Modal Box">×</span>
<img class="modal_contentClass" id="modalEnlargementID">
</div>
<div id="captionID"></div>
JS code:
for (var i = 0;i < document.getElementsByClassName("zoom_buttonClass").length;i++){
document.getElementsByClassName("zoom_buttonClass")[i].addEventListener('click', myFunction
(var attribute = this.getAttribute("id");
var photoIDstring = "photo"+counterX+"ID";
document.getElementById('myModalID').style.display = "block";
document.getElementById('captionID').style.display = "block";
document.getElementById("modalEnlargementID").src = document.getElementById(photoIDstring).src;
captionText.innerText = document.getElementById(photoIDstring).alt;
), false);
};
Well, I started again and I think I may have hit upon a solution. It seems to work.
var captionText = document.getElementById("captionID");
var howManyButtons = document.getElementsByClassName("zoom_buttonClass").length;
var buttonCollection = document.getElementsByClassName("zoom_buttonClass");
for (let i=0; i < howManyButtons; i++) {
buttonCollection[i].onclick = function() {
let photoIDstring = "photo"+(i+1)+"ID";
document.getElementById('myModalID').style.display = "block";
document.getElementById('captionID').style.display = "block";
document.getElementById("modalEnlargementID").src = document.getElementById(photoIDstring).src;
captionText.innerText = document.getElementById(photoIDstring).alt;
}
}

Run script on web whatsapp

I tried to run script with greasemonkey on web whatsapp. But not work so well.
the code need to open new windows and refresh it with content:
[1st part:]
var list = main[0].getElementsByClassName("msg");
var i;
for (i = 0; i < list.length; i++) {
list[i].innerHTML += '<button type="button" class="addButton" onclick="javascript:addNewMsg(this.parentElement)">Add</button>';
}
[2nd part:]
document.body.innerHTML += '<div style="position:absolute;bottom:20px;right:20px;z-index:80;border:1px black solid"><button type="button" id="startButton" onclick="javascript:us_openWAwindows()">Start</button></div>';
The button not working (not open new windows)..
Thx for the help.
edit: cleaned the code for presenting only the issue.
It would appear you can't use onclick attributes on this page due to its Content Security Policy.
Please try using event listeners you are attaching in JavaScript, not embedded JS code in HTML.
1) For creating the "Add" buttons it would probably be best to create it totally in JS and set all attributes there, because from first glace it looks to me like there can be multiple and you are creating and deleting them again depending on what the user does.
for (i = 0; i < list.length; i++) {
var btn = document.createElement("button");
btn.setAttribute("type", "button");
btn.setAttribute("class", "addButton");
btn.addEventListener("click", function() {
addNewMsg(this.parentElement);
});
btn.innerHTML = "Add";
list[i].appendChild(btn);
}
2) For the "Start" button which is created only once we can keep the HTML if you want and use its ID to reference it (although you could also use the same approach as I did above):
document.body.innerHTML += '<div style="position:absolute;bottom:20px;right:20px;z-index:80;border:1px black solid"><button type="button" id="startButton">Start</button></div>';
document.getElementById("startButton").addEventListener("click", us_openWAwindows);
(Note that I removed the onclick attribute from both.)

Get all buttons of a web page and delete the ones with certain background-image in Javascript

Good morning everybody, I'm a bit of newbie in javascript and other web languages.
What I want to do is get all buttons of a web page, then delete the one(s) with a specific background-image.
I understand the use of getElementsByTagName but can't do anything more.
I've started with the code above :
document.getElementsByTagName(button)
What should I do next please ?
Thanks for your help.
Just follow the steps :
Get all elements
Check each element with specific background-image
Remove the element.
HTML :
<div id="parentNode">
<button style="background-image:url('http://i.dailymail.co.uk/i/pix/2013/11/11/article-2500617-007F32C500000258-970_306x423.jpg')">First</button>
<button style="background-image:url('http://www.allgraphics123.com/ag/01/14142/14142.gif')">Second</button>
<button style="background-image:url('http://jitendravaswani.files.wordpress.com/2013/02/191356xcitefun-cartoon-pluto.jpg')">Third</button>
<button style="background-image:url('https://lh5.googleusercontent.com/-WsZ4Q7Y156A/AAAAAAAAAAI/AAAAAAAAABM/vN1-gy0xZQU/photo.jpg')">Fourth</button>
</div>
javaScript :
var imageButtons = document.getElementsByTagName("button");
var parent = document.getElementById("parentNode");
for(var index = 0; index < imageButtons.length; index++ ){
if(imageButtons[index].style.backgroundImage == "url(http://www.allgraphics123.com/ag/01/14142/14142.gif)"){
alert();
parent.removeChild(imageButtons[index]);
}
}
jsFiddle
Try this
<script type="text/javascript">
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].style.backgroundImage == "specific image") {
buttons[i].style.display = 'none';
}
}
</script>

How to put a button inside of a text entry field in a form on a website using javascript, css, html

I would like to write a greasemonkey script that make a button inside of a text entry form on some websites, so that the text entry forms would look something like this:
____________________
Username:|___________|BUTTON|
____________________
Password:|___________|BUTTON|
Is there any way I can do this with javascript, html, and css? Note that I want my greasemonkey script to work on website's who's layout I do not know, so I can't use the image repositioning trick as in this post: How do I add a "search" button in a text input field?
Okay, let's start with jQuery, since it's more concise.
$('form').each(function () {
$(this).find('input').filter(':text').each(function () {
$(this).after($('<button>').text('My Button'));
});
});
http://jsfiddle.net/xERT8/2/
Edited for non-jquery version.
Okay, here we go!
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
var form = forms[i];
var inputs = form.querySelectorAll("input[type=text]");
for (var j = 0; j < inputs.length; j++) {
var input = inputs[j];
var button = document.createElement('button');
button.innerText = 'My Button';
input.parentNode.insertBefore(button, input.nextSibling);
}
}
http://jsfiddle.net/53QQU/6/
Hope that helps.

difference between calling javascript function on body load or directly from script

i am using a javascript where in i am creating multiple div (say 5) at runtime, using javascript function, all the divs contain some text, which is again set at runtime, now i want to disable all the divs at runtime and have the page numbers in the bottom, so that whenever user clicks on the page number only that div should get visible else other should get disable, i have created a function, which accepts parameter, as page number, i enable the div whose page number is clicked and using a for loop, i disable all the other divs, now here my problem is i have created two functions, 1st (for adding divs and disabling all the divs except 1st) and writing content to it, and other for enabling the div whose page number is clicked, and i have called the Adding div function on body onload; now first time when i run, page everthing goes well, but next time when i click on any of the page number, it just gets enabled and again that AddDiv function, runs and re-enables all the divs..
Please reply why this is happening and how should i resolve my issue...
Below is my script, content for the div are coming using Json.
<body onload="JsonScript();">
<script language="javascript" type="text/javascript">
function JsonScript()
{
var existingDiv = document.getElementById("form1");
var newAnchorDiv = document.createElement("div");
newAnchorDiv.id = "anchorDiv";
var list = { "Article": articleList };
for(var i=0; i < list.Article.length; i++)
{
var newDiv = document.createElement("div");
newDiv.id = "div"+(i+1);
newDiv.innerHTML = list.Article[i].toString();
newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a> ";
existingDiv.appendChild(newDiv);
existingDiv.appendChild(newAnchorDiv);
}
for(var j = 2; j < list.Article.length + 1; j ++)
{
var getDivs = document.getElementById("div"+j);
getDivs.style.display = "none";
}
}
function displayMessage(currentId) {
var list = {"Article" : articleList}
document.getElementById("div"+currentId).style.display = 'block';
for(var i = 1; i < list.Article.length + 1; i++)
{
if (i != currentId)
{
document.getElementById("div"+i).style.display = 'none';
}
}
}
</script>
Thanks and Regards
Try adding return false; to the page link to prevent the page from being reloaded.
newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+");return false;'>"+(i+1)+"</a> ";
Your page links are reloading the page. You just have to change one line and your script works ok.
// change
newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a> ";
//to
newAnchorDiv.innerHTML += "<a href='#' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a> ";

Categories