Javascript Toggle Translations of Title onClick - javascript

I have a title within a div tag.
I need to translate the title whenever a translate button is clicked.
I have so far gotten to the point where i find the title div and want to change the contents of it by using a languageMap. But its not functioning! Any ideas?
var languageMap = {
'English1': 'French1',
'English2': 'French2'
}
function translateTitle() {
var qmTitle = document.getElementById('toolTitle')
var qmTitleText = qmTitle.innerHTML
var translatedTitle = languageMap[qmTitleText]
qmTitle.innerHTML = translatedTitle
}

Ok If you click the title it will change according to your map
What you needed to do is add an event listener for the click event
This sample shows you how to do that
I also exended your map so it translates backwards as well ..
var languageMap = {
'English1': 'French1',
'English2': 'French2',
'French1': 'English1',
'French2': 'English2'
}
var qmTitle = document.getElementById('toolTitle')
function translateTitle() {
// var qmTitle = document.getElementById('toolTitle')
var qmTitleText = qmTitle.innerHTML
var translatedTitle = languageMap[qmTitleText]
qmTitle.innerHTML = translatedTitle
}
qmTitle.addEventListener("click", translateTitle);
<h2 id="toolTitle">English1</h2>

Related

javascript dynamically remove text

I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.

Unable to get the updated id value of div eventhough it is adding in the HTML

enter image description hereI am trying to add multiple divs (containing 2 children h1 and canvas) to a div.
The added div ids are getting added in the HTML but i am not able to get the updated div ids through the api using the JavaScript.
Please find the below code in JavaScript.
Please find the attached screen shot which is showing the issue in detail in the Chrome Debugger
function addElement() {
var ni = document.getElementById('interview_div');
var userdiv = createUserDiv();
ni.appendChild(userdiv);
var canvas_id = document.getElementById('candidate_div').lastChild.getAttribute('id')
console.log(document.getElementById('candidate_div').lastChild.getAttribute('id'));
var canvas_temp = document.getElementById(canvas_id);
context = canvas_temp.getContext("2d");
drawTimeLine(20);
}
function createUserDiv(){
var div_user = document.createElement("div");
div_user.setAttribute('id','candidate_div');
var abcd = document.getElementById('uname').value;
var firstInput = createInput(abcd);
div_user.appendChild(firstInput);
var temp_canvas = document.createElement('canvas');
temp_canvas.setAttribute('id' , 'temp_canvas'+ abcd);
//width="1500" height="40"
temp_canvas.setAttribute('width','1500');
temp_canvas.setAttribute('height','40');
div_user.appendChild(temp_canvas);
return div_user;
}
function createInput(name){
var input = document.createElement('h1');
input.innerHTML = name;
//input.setAttribute('type', 'text');
//input.setAttribute('name', name+'[]');
return input;
}

i can add textbox with button but i don't know how to remove

var emails = document.getElementById('emails'),
add_link = document.createElement('a'),
template = emails.getElementsByTagName('div'),
current = template.length,
max = 20;
template = template[0];
submit1.onclick = function () {
var new_field = template.cloneNode(true);
current += 1;
new_field.innerHTML = new_field.innerHTML.replace(/1/g, current);
emails.appendChild(new_field);
if (current === max) {
add_link.onclick = null;
document.body.removeChild(add_link);
}
return false;
};
document.body.appendChild(add_link);
copy from this link
add multiple textbox using button click in javascript
how to create button for remove ,please tell me
Try using something like this.
elememt.parentNode.removeChild(element);
This question has been asked and posted on this site. Look at this link.
Remove an Element with Javascript

How to interate an array with navigation menu buttons (first, previous, next, last)

Well, one more question. Since I started learning javascript short time ago, I am almost obsessed trying new things! Here it goes:
Let's say that I have an array of strings and I want to iterate on it with a navigation menu with the buttons FIRST, PREVIOUS, NEXT, LAST.
Look at this code:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
function generatepage(article) {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
I also figured out that generatepage(thearray.length -1)would be the call for the last article, so I have solved two buttons (before generating new content I would erase it with innerHTMLbut what I cannot think about how to do are the PREVIOUS and NEXT buttons...
Do you have any suggestion about how should I get started to make working PREVIOUS and NEXT?
I attach a JSFiddle
Thank you so much for any advice!
You can save the active page in a variable outside the function:
var page = 0;
Then you don’t need to bring any page into generatepage():
function generatepage() {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[page]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
Now you can control the page from outside the function:
var next = function() {
if ( page < page.length-1 ) { page++; }
}
var prev = function() {
if ( page ) { page--; }
}
So to show the first page:
page = 0;
generatepage()
And the next:
next();
generatepage()
etc.... There are other ways too of course but this might give you an idea.
You can save a variable outside the scope of the function to memorize the current article
when you add Eventlisteners to the buttons you can call the next and previous item
but you should somehow replace the content of the div with the next one instead of appending it (i don't know a thing about manipulating dom elements)
you could try something like this:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
var currentarticle
function generatepage(article) {
if(thearray[article]) {
currentarticle = article
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.innerHTML= paragraph.innerHTML
}else {
return false
}
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
document.getElementById("next").addEventListener("click",function() {
generatepage(currentarticle + 1)
});
document.getElementById("previous").addEventListener("click",function() {
generatepage(currentarticle - 1)
});
document.getElementById("last").addEventListener("click",function() {
generatepage(thearray.length - 1)
});
document.getElementById("first").addEventListener("click",function() {
generatepage(0)
});
​
heres the Fiddle

obj is null, javascript

function init()
{
alert("init()");
/**
* Adds an event listener to onclick event on the start button.
*/
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
});
ok so what I have here is a event listerner function, the case is when viewInvitation is clicked , the program will fetch my xml file and run page master function where I created my decline button with id="declinebutton", however this does not work, the error message that i get is obj=null or the program could not find id = declinebutton, why is it so? I have created it when I called page master using dom. any help will be appreciated.
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
var subjectList;
var i;
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table=document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
var input=document.createElement("p");
var inputText=document.createTextNode("You are invited to join " + groupName + "(groupId : " + groupId +")");
input.className="style11";
var blank=document.createElement("nbps");
input.appendChild(inputText);
var acceptButton=document.createElement("input");
acceptButton.type="button";
acceptButton.id="acceptbutton";
acceptButton.value="accept";
var declineButton=document.createElement("input");
declineButton.type="button";
declineButton.id="declinebutton";
declineButton.value="decline";
table.appendChild(input);
table.appendChild(acceptButton);
table.appendChild(declineButton);
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
/**function getValueOf()
{
return i;
}**/
function declineInvitation()
{
alert("decline");
}
function acceptInvitation()
{
alert("hello");
/**var pos=getValueOf();
alert(subjectList[pos].attributes[0].nodeValue);**/
}
That's my page master function, and I definitely have created the button. but it does not work.
Try calling your function like this:
window.onload=init;
The javascript runs as the page loads. At that point, the element does not yet exist in the DOM tree. You'll need to delay the script until the page has loaded.
The example you gave doesn't create the "Decline" button, as your question suggests it should. If it should, you might want to look at that.
Of course, if the button already exists, please disregard this answer.
You have a listener inside a listener. Is that right?
What about this?:
function init(){
alert("init()");
/** * Adds an event listener to onclick event on the start button. */
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
}
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
As far as I understand, you create button with id="declinebutton" for each entry from xml, is that right?
If yes, I'd suggest you to generate different id's for each button (for example, append line index to 'declinebutton', so you have buttons 'declinebutton0', 'declinebutton1' an so on), and assign event listener to buttons separately in the loop.

Categories