Jquery append Concatenation onclick - javascript

I am trying to pass two variables one is having integer and other is having some string,say i want to pass id,name
<div class='redstatus' onclick='redStatus("+Id+","+name+")'><span class='countspan''>"+red_count+"</span></div>
In the above code in onclick function if i pass only id <div class='redstatus' onclick='redStatus("+Id+")'><span class='countspan''>"+red_count+"</span></div> it is working fine.
I want to send one more parameter name along with id separated by comma
<div class='redstatus' onclick='redStatus("+Id+","+name+")'><span class='countspan''>"+red_count+"</span></div>
it is not working.I need help on this.
for(var i in appData ){
console.log("Data"+JSON.stringify(appData));
for(j in appData.LOB){
var LOBId = appData.LOB[j].LOBID;
LOBName = appData.LOB[j].LOBName;
var LOBRef = appData.LOB[j].LOBRef;
var LOBNameRef = appData.LOB[j].LOBNameRef;
//console.log("LOBId"+LOBId+"LOBName"+LOBName);
$(".left_div").append("<div class='left_lob_name'>"+LOBName+"</div>");
streamInRed = [];
streamInAmber = [];
streamInGreen = [];
currentItemRed = [LOBId];
currentItemAmber = [LOBId];
currentItemGreen = [LOBId];
//$("."+LOBNameRef+"").append("<div id="+LOBId+" style='height:74vh;overflow-y:auto;'><table class='table table-bordered' ><thead><tr><th>StreamName</th><th>BusinessSLA Description</th><th>Status</th><th>Business SLA</th><th>Forecast Completion Time</th><th>Actual Completion Time</th><th>JobName</th></tr></thead><tbody class='"+LOBRef+"'></tbody></table></div>");
for(var k in appData.LOB[j].Streams.Stream){
//console.log("Streams"+JSON.stringify(appData.LOB[j].Streams.Stream));
var streamId = appData.LOB[j].Streams.Stream[k].streamId;
var streamName = appData.LOB[j].Streams.Stream[k].streamName;
var Status = appData.LOB[j].Streams.Stream[k].Status;
var jobName = appData.LOB[j].Streams.Stream[k].JobName;
var BSD= appData.LOB[j].Streams.Stream[k].BusinessSLADescrition;
var BSLA = appData.LOB[j].Streams.Stream[k].BusinessSLA;
var FCT = appData.LOB[j].Streams.Stream[k].ForecastCompletionTime;
var ACT = appData.LOB[j].Streams.Stream[k].ActualCompletionTime;
var RAGStatus = appData.LOB[j].Streams.Stream[k].RAGStatus;
if(Status == "red"){
//$("."+LOBName+"").append("<div class='streamcolor_red test' data-name='1'>"+streamName+"</div>");
//$("."+LOBRef+"").append("<tr class='test' data-name='1'><td style='background-color:#f3180d;color:#fff;'>"+streamName+"</td><td>"+BSD+"</td><td>"+RAGStatus+"</td><td>"+BSLA+"</td><td>"+FCT+"</td><td>"+ACT+"</td><td>"+jobName+"</td></tr>");
red_count = red_count+1;
currentItemRed = [streamName,BSD,RAGStatus,BSLA,FCT,ACT,jobName];
streamInRed.push(currentItemRed);
//redStatus();
//console.log("streamInRed"+streamInRed);
}else if(Status == "amber"){
//$("."+LOBRef+"").append("<tr class='test' data-name='2'><td style='background-color:rgba(243, 168, 15, 0.9215686274509803);color:#fff;'>"+streamName+"</td><td>"+BSD+"</td><td>"+RAGStatus+"</td><td>"+BSLA+"</td><td>"+FCT+"</td><td>"+ACT+"</td><td>"+jobName+"</td></tr>");
//$("."+LOBName+"").append("<div class='streamcolor_amber test' data-name='2'>"+streamName+"</div>");
amber_count = amber_count+1;
currentItemAmber = [streamName,BSD,RAGStatus,BSLA,FCT,ACT,jobName];
streamInAmber.push(currentItemAmber);
}else {
//$("."+LOBRef+"").append("<tr class='test' data-name='3'><td style='background-color:green;color:#fff;'>"+streamName+"</td><td>"+BSD+"</td><td>"+RAGStatus+"</td><td>"+BSLA+"</td><td>"+FCT+"</td><td>"+ACT+"</td><td>"+jobName+"</td></tr>");
//$("."+LOBName+"").append("<div class='streamcolor_green test' data-name='3'>"+streamName+"</div>");
green_count = green_count+1;
currentItemGreen=[streamName,BSD,RAGStatus,BSLA,FCT,ACT,jobName];
streamInGreen.push(currentItemGreen);
}
//console.log("streamId"+streamId+"streamName"+streamName+"Status"+Status);
}
console.log("LOBId",LOBId);
console.log("sep_symbol",sep_symbol);
console.log("syb",syb);
console.log("LOBNameRef",LOBNameRef);
var tempvar = "'"+LOBNameRef+"'";
console.log("tempvar"+LOBId +sep_symbol +tempvar);
$("<div style='text-align:center;height:5vh;margin:2vw;'> <div class='redstatus' onclick='redStatus("+LOBId+","+LOBNameRef+")'><span class='countspan''>"+red_count+"</span></div> <div class='amberstatus' onclick='amberStatus("+LOBId+")'><span class='countspan'>"+amber_count+"</span></div> <div class='greenstatus' onclick='greenStatus("+LOBId+")'><span class='countspan'>"+green_count+"</span></div></div>").appendTo(".right_div");
red_count = 0;
amber_count = 0;
green_count = 0;
//var Streams = appData.LOB[j].Streams;
//console.log("Before"+$wrapper);
//var $wrapper = $('.'+LOBRef+'');
//console.log("after"+$wrapper);
//$wrapper.find('.test').sort(function (a, b) {
/// return +a.dataset.name - +b.dataset.name;
//})
//.appendTo( $wrapper );
}
}
i have added the code for your reference

The problem is with the line
$("<div style='text-align:center;height:5vh;margin:2vw;'> <div class='redstatus' onclick='redStatus("+LOBId+","+LOBNameRef+")'><span class='countspan''>"+red_count+"</span></div> <div class='amberstatus' onclick='amberStatus("+LOBId+")'><span class='countspan'>"+amber_count+"</span></div> <div class='greenstatus' onclick='greenStatus("+LOBId+")'><span class='countspan'>"+green_count+"</span></div></div>").appendTo(".right_div");
which, more prettily, and without the inline handlers, can be constructed like:
const htmlStr = `
<div style='text-align:center;height:5vh;margin:2vw;'>
<div class='redstatus'><span class='countspan'>${red_count}</span></div>
<div class='amberstatus'><span class='countspan'>${amber_count}</span></div>
<div class='greenstatus'><span class='countspan'>${green_count}</span></div>
</div>
`;
You can pass the HTML string to jQuery to get a jQuery collection, then select the inner divs and add a listener to each:
const $row = $(htmlStr);
$row.find('.redstatus').on('click', () => redStatus(LOBId, LOBNameRef));
$row.find('.amberstatus').on('click', () => amberStatus(LOBId, LOBNameRef));
$row.find('.greenstatus').on('click', () => greenStatus(LOBId, LOBNameRef));
$row.appendTo(".right_div");
(or pass whatever parameters you want to the status functions - no quote escaping required!)
Make sure the LOBIds and LOBNameRefs don't reassign themselves in other iterations of the loop - declare them with const, eg:
const LOBId = appData.LOB[j].LOBID;
const LOBName = appData.LOB[j].LOBName;
const LOBRef = appData.LOB[j].LOBRef;
so they're scoped to the block, not to the function.
(It would also probably be good to have just a single <color>Status function, rather than three separate standalone functions (which probably all do something somewhat similar) - too much repetition should be avoided)

You want to concatenate two parameters passed to a function, do not enclose variables in single or double quotes, it should be as :onclick="redStatus(Id,name)"
function redStatus(Id,name){
var result = Id+'_'+name;
document.getElementsByClassName('countspan')[0].innerText = result;
}
<!DOCTYPE html>
<html>
<head>
<title>Append Two Params</title>
</head>
<body>
<div onclick="redStatus(1,'name')">Append Two Params</div>
<span class='countspan'></span>
</body>
</html>

Related

Can i call another function inside the GetElement in Javascript

I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">

Passing array -- scope

I want to pass an array from one external .js file to another.
Each of these files works fine by themselves, but I am having a problem passing the array from pickClass.js to displayStudent.js, and getting the names and "remaining" value to display in the html file. I know it has something to do with how the arrays are declared, but I can't seem to get it to work properly.
The first file declares the array choice:
(masterStudentList.js):
var class1 = ['Brown, Abe','Drifter, Charlie','Freed, Eve'];
var class2 = ['Vole, Ug','Xylo, William','Zyzzyx, Yakob'];
The second picks which array to use based on the radio buttons (pickClass.js):
var classPicked = array(1);
function randomize(){
return (Math.round(Math.random())-0.5); }
function radioResult(){
var chooseClass = document.getElementsByName("chooseClass");
for (i = 0; i < chooseClass.length; i++){currentButton = chooseClass[i];
if (currentButton.checked){
var selectedButton = currentButton.value;
} // end if
} // end for
var output = document.getElementById("output");
var response = "You chose ";
response += selectedButton + "\n";
output.innerHTML = response;
chosenClass = new Array();
if (selectedButton == "class1")
{chosenClass = class1;}
else
{chosenClass = class2;}
var text = "";
var nametext = "";
var i;
for (i = 0; i < chosenClass.length; i++) {
text += chosenClass[i]+ ' / ';
}
var showText = "";
l = chosenClass.length;
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
//return = classPicked;
document.getElementById("classList").innerHTML = classPicked;
} // end function
This works properly.
I then want to pass "classPicked" to another .js file (displayStudent.js) which will randomize the student list, loop and display the students for a few seconds, and then end with one student name.
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5); }
function showBasket(){
mixedBasket = basket.sort( randOrd ); //randomize the array
var i = 0; // the index of the current item to show
document.getElementById("remaining").innerHTML = basket.length;
fruitDisplay = setInterval(function() {
document.getElementById('showStud')
.innerHTML = mixedBasket[i++]; // get the item and increment
if (i == mixedBasket.length) i = 0; // reset to first element if you've reached the end
}, 100); //speed to display items
var endFruitDisplay = setTimeout(function()
{ clearInterval(fruitDisplay);
var index = mixedBasket.indexOf(document.getElementById('showStud').innerHTML);
mixedBasket.splice(index,1);
}, 3500); //stop display after x milliseconds
}
Here is the html (master.html). It's just rough -- I'll be working on the layout later:
<html>
<head>
<script src="masterStudentList.js" type="text/javascript"></script>
<script src="pickClass.js" type="text/javascript"></script>
<script src="displayStudent.js" type="text/javascript"></script>
</head>
<body>
<h2>Choose Class</h2>
<form action = "">
<fieldset>
<input type = "radio"
name = "chooseClass"
id = "radSpoon"
value = "class1"
checked = "checked" />
<label for = "radSpoon">Class 1</label>
<input type = "radio"
name = "chooseClass"
id = "radFlower"
value = "class2" />
<label for = "radFlower">Class 2</label>
<button type = "button"
onclick = "radioResult()"> Choose Class
</button>
<div id = "output">
</fieldset>
</form>
</div>
<center>
<h1> <span id="chooseStud"></span><p></h1>
<script> var fruitSound = new Audio();
fruitSound.src = "boardfill.mp3";
function showFruitwithSound()
{
fruitSound.play(); // Play button sound now
showBasket()
}
</script>
Remaining: <span id = "remaining" ></span>
<p>
<button onclick="showFruitwithSound()">Choose Student</button>
</center>
pickedClassList = <p id = classList> </p>
</body>
</html>
You shouldn't use global variable like this (I encourage you to read more on this theme) and I'm not sure I understand what you're trying to do... but the solution of your issue should be to move the basket = classPicked; line into your showBasket method :
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
// whatever
}
should be :
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
basket = classPicked; //This is where the array should be passed
// whatever
}
This way, each time you call showBasket, this method will use the last value of classPicked.
Otherwise, basket will always keep the reference on the first value of classPicked.
Why ? because each time you assign a new Array to the basket variable (classPicked = Array(l);) instead of changing directly it's content by :
emptying it : while (classPicked.length > 0) { classPicked.pop(); }
and then adding new data : classPicked.concat(chosenClass)
You can't pass things to files; you could call a function defined in displayStudent.js, pass it classPicked, and have it assign it to basket.
I noticed this at the end of your second chunk of code ...
} // end function
This could indicate the classPicked is declared inside a function (I don't see one on the code). Because it is inside function scope, your set of code that is trying to use it cannot.
Push the declaraction of classPicked outside of the function.
var classPicked = Array(1);
function thisusesclasspicked() {
...
Also, please start indenting your code properly, it will become much easier to maintain and read.
UPDATE FROM COMMENTS:
I see the declaration now ...
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
... however, you are re-assigning the array with an element of one just before you attempt to make modifications to it ... You are emptying it there: classPicked = Array(l);

How to separate javascript and markup in case of a script line with parameters?

Separating javascript and markup is easy when the script doesn't have parameters. But how is it done with inline script lines that do? Example:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add"
onclick="showSelectTables('none','none','none','table','none','none')">
</td>
(....)
<script>
function showSelectTables(set1a,set1b,set1c,setSetup,set2,set3) {
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
.
I've tried all varieties I can think of, but all I'm getting is error reports, 'undefined' or the silent treatment from the browser. Is it possible at all, and if so, how? I would be looking for a vanilla javascript solution.
EDIT: see here for what I'm trying to achieve: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript, section 2.
I suggest you to change your HTML generation logic to generate the followings:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add" />
</td>
<script>
// just show 2 variables for demo
var settings = { change-add : { set1a: 'some_value', set1b: 'some_value' } }
$('#change-add').click(function() {
showSelectTables($(this).attr('id'));
});
function showSelectTables(the_id) {
var set1a = settings[the_id]['set1']; // which returns 'some_value'
// similar for set1b,set1c,setSetup,set2,set3
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
Note: this assumes you use jQuery.
An important note: there is nothing wrong to use inline onclick, but it's a better pattern to separate JS and HTML

How to create a clickable list of divs with sub items using JavaScript

I want to create a list of clickable divs from arrays using Javascript, where the list structure has to be something like this:-
<div id="outerContainer">
<div id="listContainer">
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
</div>
</div>
I want to extract the values of itemId, itemTitle and itemStatus from three arrays itemIdData[ ], itemTitleData[ ] and itemStatusData[ ] respectively, to create the whole list.
Also, when I click on any of the listElements, I want an alert showing the itemId. Can anyone help me with this problem.
If you're using jQuery, then try something like this:
$("#listContainer").on("click", "div", function () {
console.log("jQuery Event Delegation");
alert($(this).find(">:first-child").attr("id"));
});
It's possible to write the same thing without jQuery, but will take further lines of code - I'm conveying the idea of delegation here (there are extensive existing docs and examples on the JQuery site, and here on this site).
NB: the code you're submitted in the question can't(shouldn't) have multiple DOM elements with same IDs (that's what classes are for - for semantically similar elements). Also, trying to emulate a list using divs instead of li elements is perhaps not best practice.
After a bit of experimentation, understood what I was doing wrong and how to get it done.
Here's the code:-
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
for (var i = 0; i < json.length; i++) {
//create the element container and attach it to listContainer.
var listElement = document.createElement("div");
listElement.id = i;
listElement.className = "listItemContainer";
listElement.addEventListener("click", function(e){
var itemId = e.target.children[1].innerHTML;
alert(itemId);
});
listContainer.appendChild(listElement);
//create and attach the subchilds for listElement.
var itemTitle = document.createElement("span");
itemTitle.innerHTML = postTitleData[i];
itemTitle.id = 'title'+i;
itemTitle.className = "itemTitle";
listElement.appendChild(itemTitle);
var itemId = document.createElement("div");
itemId.innerHTML = postIdData[i];
itemId.id = 'id'+i;
itemId.className = "itemId";
listElement.appendChild(itemId);
var itemStatus = document.createElement("span");
itemStatus.innerHTML = postStatusData[i];
itemStatus.id = 'status'+i;
itemStatus.className = "itemStatus";
listElement.appendChild(itemStatus);
}
Tried something like this which isn't quite working!
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
var listElement = document.createElement("div");
listContainer.appendChild(listElement);
listElement.className = "listItemContainer";
for (var i = 0; i < json.length; i++) {
var itemId = document.createElement("div");
itemId.innerHTML = idData[i];
listElement.appendChild(itemId);
itemId.className = "itemId";
var itemTitle = document.createElement("div");
itemTitle.innerHTML = titleData[i];
listElement.appendChild(itemTitle);
itemTitle.className = "itemTitle";
var itemStatus = document.createElement("div");
itemStatus.innerHTML = statusData[i];
listElement.appendChild(itemStatus);
itemStatus.className = "itemStatus";
listElement.appendChild(document.createElement("hr"));
var elementId = 'ListElement'+i;
listElement.id = elementId;
listElement.addEventListener("click", function(){
alert(document.getElementById(elementId).innerHTML);
});
}

How to loop same javascript code for more than one div elements?

I have made three "boxes" and each box contains a button. When I click the button, box hiding, when click again, box appears.
This is my html code:
<div id="SC1_A_"> <!-- BOX -->
<div id="SC1_B_" onClick="SC1();" class="something"> </div> <!-- BUTTON -->
</div>
<div id="SC2_A_">
<div id="SC2_B_" onClick="SC2();" class="something"> </div>
</div>
<div id="SC3_A_">
<div id="SC3_B_" onClick="SC3();" class="something"> </div>
</div>
This is my javascript code:
<script type="text/javascript">
function SC1(){
var SC1_A = document.getElementById('SC1_A_);
var SC1_B = document.getElementById('SC1_B_);
if (SC1_A.style.display == 'block' || SC1_A.style.display == ''){
SC1_A.className = 'something';
SC1_B.className = 'something else';}
else {SC1_A.className = 'something else';
SC1_B.className = 'something';}
}
}
</script>
The example above works, but I have to make three similar scripts for each button. So I though to make something like this script below, using for loop. As you can imagine it didn't work. Any idea how can I make it work???
<script type="text/javascript">
for (i=1; i<10; i++){
function SCi(){
var SCi_A = document.getElementById('SC'+i+'_A_');
var SCi_B = document.getElementById('SC'+i+'_B_');
if (SCi_A.style.display == 'block' || SCi_A.style.display == ''){
SCi_A.className = 'something';
SCi_B.className = 'something else';}
else {SCi_A.className = 'something else';
SCi_B.className = 'something';}
}
}
</script>
Please don't down-vote if you think question is too easy, but just give me your help here!!! Thank you in advance!!!
You're on the right track, you just need to learn the right syntax for what you are trying to express:
var SC = [];
First off, to have a lot of different functions, so instead of attempting to name them differently (which you were trying to do), we are going to just store each function in a different index in the SC array.
for (var i = 1; i < 10; i++) {
SC[i] = (function () {
var SC_A = document.getElementById('SC' + i + '_A_');
var SC_B = document.getElementById('SC' + i + '_B_');
return function () {
if (SC_A.style.display === 'block' || SC_A.style.display === '') {
SC_A.className = 'something';
SC_B.className = 'something else';
} else {
SC_A.className = 'something else';
SC_B.className = 'something';
}
}
})();
}
Now, to call these functions you would do SC[1](), SC[2](), ... So you can either put that in each onclick in your HTML, or you could bind the events from the javascript.
Edit: I forgot to mention this because it isn't directly related to the syntax of the code, but the calls to 'document.getElementByIdwill not work until the document is fully loaded. So if you just put the script directly between to` tags it won't work. You have two choices. You either can keep the current code, but run it when the page loads. Or, you could restructure the code like this:
var SC = [];
for (var i = 1; i < 10; i++) {
SC[i] = (function (i) {
return function () {
var SC_A = document.getElementById('SC' + i + '_A_');
var SC_B = document.getElementById('SC' + i + '_B_');
if (SC_A.style.display === 'block' || SC_A.style.display === '') {
SC_A.className = 'something';
SC_B.className = 'something else';
} else {
SC_A.className = 'something else';
SC_B.className = 'something';
}
}
})(i);
}
What's happening here is you are calling document.getElementById every time the button is clicked, instead of just once when the function is created. Slightly less efficient, but it works.
You define each section on the page as calling the one function and passing in the name of the other .
<div id="SC1_A_"> <!-- BOX -->
<div id="SC1_B_" onClick="SC('SC1_A_');" class="something"> </div> <!-- BUTTON -->
</div>
<div id="SC2_A_">
<div id="SC2_B_" onClick="SC('SC2_A_');" class="something"> </div>
</div>
<div id="SC3_A_">
<div id="SC3_B_" onClick="SC('SC3_A_');" class="something"> </div>
</div>
There is just one function used for all of them
function SC(nameOfA){
var SCi_A = document.getElementById(nameOfA);
var SCi_B = this;
if (SCi_A.style.display == 'block' || SCi_A.style.display == ''){
SCi_A.className = 'something';
SCi_B.className = 'something else';
} else {
SCi_A.className = 'something else';
SCi_B.className = 'something';}
}
}
here you can use this function on every click:
<div id="SC1_A_"> <!-- BOX -->
<div id="SC1_B_" onClick="SC(event)" class="something"> </div> <!-- BUTTON -->
</div>
<script type="text/javascript">
function SC(event){
var SCA = event.currentTarget.parentNode;
var SCB = event.currentTarget;
................
}
</script>
Your code is defining a function named SCi 8 times. I think if you swap the first two lines you will get what you want.
You're redefining the same function (function SCi) eight times. The only version of the function that is retained is the version that's defined last. Going by your code, you're only creating a function that can work with the 8th box.

Categories

Resources