Search code examples
javascriptarraysdompromptfunc

?JS How to exit from function?


I need to exit from mine.onclick = function so can anyone help me?? I'm new in js! I tried to write the word game and I need to write the function, when I'm clicking on the button I need to move the button, but its not working 3th time

    //creating div  
var div = document.createElement('div');
div.innerHtml = '';
document.body.appendChild(div);
div.classList.add('main');

//creating divsec 
var divsec = document.createElement('div');
divsec.innerHtml = '';
document.body.appendChild(divsec);
divsec.classList.add('submain');

//creating array for words
var arr = prompt("Write your word or sentance here and don't accept your apponent to see that!");
array = arr.split('');
array = array.sort();
console.log(array);
alert("Let's construct the word!");

var main = document.getElementsByClassName('main');
var divsec = document.getElementsByClassName('submain');
for(var i = 0; i < arr.length; i++){
    var button = document.createElement('button');
    divsec[0].appendChild(button);
    button.innerHTML = array[i];
    button.onclick = function(){
        mainp = main[0].appendChild(this);
        mainp.onclick = function (){
            divsec[0].appendChild(this);
        }
    }
}

Solution

  • Is this the answer you're looking for?

    //creating div  
    var div = document.createElement('div');
    div.innerHtml = '';
    document.body.appendChild(div);
    div.classList.add('main');
    
    //creating divsec 
    var divsec = document.createElement('div');
    divsec.innerHtml = '';
    document.body.appendChild(divsec);
    divsec.classList.add('submain');
    
    //creating array for words
    var arr = prompt("Write your word or sentance here and don't accept your apponent to see that!");
    array = arr.split('');
    array = array.sort();
    console.log(array);
    alert("Let's construct the word!");
    
    var main = document.getElementsByClassName('main');
    var divsec = document.getElementsByClassName('submain');
    for(var i = 0; i < arr.length; i++){
        var button = document.createElement('button');
        divsec[0].appendChild(button);
        button.innerHTML = array[i];
        button.onclick = function(){
    			if (this.parentNode.className === 'main') divsec[0].appendChild(this)
    			else main[0].appendChild(this);
            }
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>

    If it's not, please clarify your question and give an example of what is the desired effect on clicking a single button. I'm also not sure what you mean by exit the function. It seemed fine to me.

    You stated that you need a button to move, but you didn't state how does it need to move.