document.write javascript Black jack game - javascript

Currently, I am trying to make a black jack game using javascript.
so far I have the dealer's card and the player's card. The problem occurs when the player decides to get another card. It seems like document.write is late in writing the string onto the webpage.
while (totalP < 21)
{
r = confirm("Hit?");
if (r==true)
{
document.write("<center><br>You chose to hit. </center>");
p[counter] = deck[Math.floor(Math.random() * deck.length)];
document.write("<center><br>" + x + "'s next card: " + p[counter] + "</center>");
totalP = total(p, totalP);
if (totalP > 21)
{
for (var i=0; i<p.length; i++)
{
value = p[i].substring(0,p[i].length-1);
if (value == "A")
{
totalP = totalP - 10;
break;
}
else if (i == p.length - 1)
{
document.write("<center><br>You busted. Total = " + totalP + " > 21. Dealer Wins!</center>");
break;
}
}
}
}
The string "You chose to hit." shows up and even after i press ok. the text that should display the next card doesnt show up on the webpage and the confirm dialog box "You chose to hit." shows up again, until the second ok or until the player's card in hand is greater than 21.
If someone can help me on this it would be much appreciated. After researching on the internet and troubleshooting on my own, i can only think of the document.write being unreliable and slow compared to the other javascript code.

Don't use document.write. As you see, it completely replaces the content of the document.
Instead of that you should create a HTML document with some HTML elements in which you can place text.
You can select HTML nodes by their id property. When you have a HTML node like this:
<div id="myDiv"></div>
you can use
var div = document.getElementById("myDiv");
to access that div in your Javascript code. You can then use
div.innerHTML = "Hello World!";
to change the text of that div. You can also create new HTML elements like this:
var newDiv = document.createElement("div");
newDiv.innerHTML = "I am a newly created div!";
var oldDiv = document.getElementById("myDiv");
oldDiv.appendChild(newDiv);
Afterwards your HTML document will look like this:
<div id="myDiv">Hello World!<div>I am a newly created div!</div></div>

Related

Adding clickable buttons or links for side bar

I'm having trouble adding links or buttons to my side bar dynamically. I'm trying to use JavaScript to add the appropriate amount of elements or buttons(I don't know what is better). In essence this is used to make a JS quiz website where each of the buttons in the sidebar will jump you to the question(to make it more clear: Question 4 takes you to 4th question and so on)
This is my side bar:
<div id="mySidenav" class="sidenav">
×
Question
</div>
My JS trying to make the elements but failing to do so:
//add question numbers to the side bar
function questionNav(){
for(var i = 0; i < numberOfQuestions; i++){
document.getElementById("mySidenav").innerHTML = "Question " + (i+1) + "<br/>";
//var newSideBarElm = "Question " + (i+1) + "<br/>";
//document.getElementById("mySidenav").insertAdjacentHTML = ('beforeend',newSideBarElm);
}
}
I've been trying numerous different methods but I can't get it to work and would greatly appreciate if someone was able to help me.
Here is the full code of the site in case you would like to see how I'm doing everything else: https://pastebin.com/hrSADLQy
So assuming that I understand your question correctly, what you are currently doing is targeting the div with the id 'mySideNav' and overwriting its content by assigning a new value to its innerHTML attribute. What you should be doing instead is
Create a new anchor element
Use the innerHTML attribute to insert your desired value (i.e "Question N")
Append your newly created element to your 'mySideNav' div element.
I wrote a small demo for you to see my answer in action, but will post my code below this answer for you to see as well.
// Grab and Store Element to append questions to
var mySideNav = document.getElementById('mySidenav');
// Designate number of questions
var numberOfQuestions = 10;
// Loop as many times as there are questions
for (let i = 0; i < numberOfQuestions; i++) {
// Step 1: Create a new anchor element
let newQuestion = document.createElement('a');
// Assign href to whatever you want
newQuestion.href = '#';
// Step 2: Use the innerHTML attribute to insert your desired value
newQuestion.innerHTML = 'Question ' + i + '<br>';
// Step 3: Append your newly created element to your 'mySideNav' div element.
mySideNav.appendChild(newQuestion);
}
I hope this helps!
According to your question and the code you provided i think you need to define a div with an onclick() property to make the corresponding question visible. That could be something like this (assuming you can access the number of questions inside this function):
function questionNav(){
for(var i = 0; i < numberOfQuestions; i++){
document.getElementById("mySidenav").innerHTML += "<div style='cursor:pointer' onclick=navigateToQuestion(" + (i+1) + ")/> Question " + (i+1) + "</div>";
}
}
And then define a the onclick function "navigateToQuestion" to show the question that is passed as parameter, maybe could be somethink like this:
function navigateToQuestion(question){
document.getElementById("question_" + currentQuestionInView).style.display = "none";
currentQuestionInView = question;
document.getElementById("question_" + question).style.display = "block";
}
Haven't tested the code but i think it should work.
Hope you get your problem solved :)

Toggle function on html click event

I'm trying to add a simple "Read more" button to a page. I managed to prepare a working function that hides the maximum characters within an element. And to call the function I've prepared a button in the HTML with a "onclick" event to call the function.
Now a couple things happen that shouldn't. The button should reveal the hidden text but the opposite happens and everytime the button is clicked more characters are removed until I'm left with only the dots even though I have a var that limits the characters to 15. I have spent too much time trying to figure this out knowing this is probably basic jQuery. I apologize if that is the case I just hope someone can point out what I'm doing wrong here.
HTML:
<button class="content-toggle" onclick="textCollapse()">Read more</button>
jQuery:
function textCollapse() {
var limit = 15;
var chars = jQuery(".field-content p").text();
if (chars.length > limit) {
var visiblePart = jQuery("<span class='visiblepart'> "+ chars.substr(0, limit) +"</span>");
var dots = jQuery("<span class='dots'>... </span>");
jQuery(".field-content p").toggle()
.empty()
.append(visiblePart)
.append(dots)
}
};
I would save full text content into outer variable and keep it there. There is no need to requery text content every time a button is clicked. Also, it's better to have a variable that would store a state for the text - collapsed or not instead of comparing each time.
var fullText = jQuery(".field-content p").text();
var collapsed = false;
function textCollapse() {
var limit = 15;
if (collapsed) {
var visiblePart = jQuery("<span class='visiblepart'> " + fullText + "</span>");
jQuery(".field-content p")
.empty()
.append(visiblePart)
collapsed = false;
} else {
var visiblePart = jQuery("<span class='visiblepart'> " + fullText.substr(0, limit) + "</span>");
var dots = jQuery("<span class='dots'>... </span>");
jQuery(".field-content p")
.empty()
.append(visiblePart)
.append(dots)
collapsed = true;
}
}
Also, I don't think you need to call toggle() since all operations are performed synchronously and there's no need to hide p element before emptying and appending nodes.

Any way to prevent losing focus when clicking an input text out of tinymce container?

I've made this tinymce fiddle to show what I say.
Highlight text in the editor, then click on the input text, highlight in tinyMCE is lost (obviously).
Now, I know it's not easy since both, the inline editor and the input text are in the same document, thus, the focus is only one. But is there any tinymce way to get like an "unfocused" highlight (gray color) whenever I click in an input text?
I'm saying this because I have a customized color picker, this color picker has an input where you can type in the HEX value, when clicking OK it would execCommand a color change on the selected text, but it looks ugly because the highlight is lost.
I don't want to use an iframe, I know that by using the non-inline editor (iframe) is one of the solutions, but for a few reasons, i can't use an iframe text editor.
Any suggestion here? Thanks.
P.S: Out of topic, does any of you guys know why I can't access to tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global var was overwritten by the tinymce select dom element of the page itself. I can't execute a tinyMCE command lol.
Another solution:
http://fiddle.tinymce.com/sBeaab/5
P.S: Out of topic, does any of you guys know why I can't access to
tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global
var was overwritten by the tinymce select dom element of the page
itself. I can't execute a tinyMCE command lol.
Well, you can access the tinyMCE variable and even execute commands.
this line is wrong
var colorHex = document.getElementById("colorHex")
colorHex contains input element, not value.
var colorHex = document.getElementById("colorHex").value
now it works ( neolist couldn't load, so I removed it )
http://fiddle.tinymce.com/DBeaab/1
I had to do something similar recently.
First off, you can't really have two different elements "selected" simultaneously. So in order to accomplish this you're going to need to mimic the browser's built-in 'selected text highlight'. To do this, you're going to have to insert spans into the text to simulate highlighting, and then capture the mousedown and mouseup events.
Here's a fiddle from StackOverflow user "fullpipe" which illustrates the technique I used.
http://jsfiddle.net/fullpipe/DpP7w/light/
$(document).ready(function() {
var keylist = "abcdefghijklmnopqrstuvwxyz123456789";
function randWord(length) {
var temp = '';
for (var i=0; i < length; i++)
temp += keylist.charAt(Math.floor(Math.random()*keylist.length));
return temp;
}
for(var i = 0; i < 500; i++) {
var len = Math.round(Math.random() * 5 + 3);
document.body.innerHTML += '<span id="'+ i +'">' + randWord(len) + '</span> ';
}
var start = null;
var end = null;
$('body').on('mousedown', function(event) {
start = null;
end = null;
$('span.s').removeClass('s');
start = $(event.target);
start.addClass('s');
});
$('body').on('mouseup', function(event) {
end = $(event.target);
end.addClass('s');
if(start && end) {
var between = getAllBetween(start,end);
for(var i=0, len=between.length; i<len;i++)
between[i].addClass('s');
alert('You select ' + (len) + ' words');
}
});
});
function getAllBetween(firstEl,lastEl) {
var firstIdx = $('span').index($(firstEl));
var lastIdx = $('span').index($(lastEl));
if(lastIdx == firstIdx)
return [$(firstEl)];
if(lastIdx > firstIdx) {
var firstElement = $(firstEl);
var lastElement = $(lastEl);
} else {
var lastElement = $(firstEl);
var firstElement = $(lastEl);
}
var collection = new Array();
collection.push(firstElement);
firstElement.nextAll().each(function(){
var siblingID = $(this).attr("id");
if (siblingID != $(lastElement).attr("id")) {
collection.push($(this));
} else {
return false;
}
});
collection.push(lastElement);
return collection;
}
As you can see in the fiddle, the gibberish text in the right pane stays highlighted regardless of focus elsewhere on the page.
At that point, you're going to have to apply your color changes to all matching spans.

detecting a div's position based on it's attaribute

I have three divs and I want to execute a command on a div that happens to be on top of the other divs in a container without referencing it's name or id.I am randomizing the position of the divs and I basically want the div whose height is equal to 10px to change it's color attribute to red when a specific number is generated, whilst the other divs maintain their default color. I have tried the following but I can't think of any way to do this without using the div's id.
var current = 0;
current++;
var topArrtcard = document.getElementById("card-answer");
var topArrtcard1 = document.getElementById("card-answer1");
var topArrtcard2 = document.getElementById("card-answer2");
if(current === 0 ){
topArrtcard.style.color = "red"; // is it possible not use the id in order to make the change
topArrtcard1.style.color = " #996600";
topArrtcard2.style.color = " #996600";
}else if(current === 1 )
{
topArrtcard.style.color = "#996600";
topArrtcard1.style.color = "red";
topArrtcard2.style.color = " #996600";
}else if(current === 2){
topArrtcard.style.color = "#996600";
topArrtcard1.style.color = " #996600";
topArrtcard2.style.color = "red";
}else {
topArrtcard.style.color = "#996600";
topArrtcard1.style.color = " #996600";
topArrtcard2.style.color = "#996600";
}
the variable current increments by 1 each time the page is loaded. I hope this is clear. Thank you in advance.
If you are not opposed to using jQuery (and why would you be? In many ways it's simpler than javascript with much less to type)...
I cannot see from your code (at this moment) what will trigger an event that you can use to do the testing that you want.
However, if something does happen to the DIV, then perhaps you can use that event to make the changes you want. You would reference the changed DIV as this.
Here is an example that looks somewhat similar

showing context menu in contentEditable div

I have a contentEditable div with following text for example:
<div contentEditable='true'> This document is classified</div>
Now for example if user clicks on 'm' in word document I want to show a context menu containing few text choices. That context menu will be contained in a div element. I want to replace the word "document" with the option(text) selected by user from context menu. In my view I have to find absolute position of click to show context menu and then I have to find space elements before and after the caret position and then replace the selection with option selected from context menu. Any idea how I can do it using JavaScript and jQuery?
Edit:
one part of my question is about context menu and other the more important is how i can detect the word on wchich user has clicked on in contentEditable div or in text area on the other hand. my goal is something like in below picture
actually i want to make a similar transliteration application. the process of script conversion from roman to Urdu has been done however i m facing lot of problems in user interface development on the web. google transliteration application can be found here. i hope someone can help me in getting word under user's mouse and display a context menu containing few choices.
You may want to have a look at some of the existing context menu plugins
http://www.trendskitchens.co.nz/jquery/contextmenu/
http://labs.abeautifulsite.net/projects/js/jquery/contextMenu/demo/
http://plugins.jquery.com/plugin-tags/context-menu
To get the currently selected word in a text area, have a look at the fieldSelection plugin.
So using the second plugin and fieldSelection (Disclaimer: I think the indexing regarding string replacement is slightly off - have not fully tested)
Javascript
$(document).ready(function () {
//replace
$("#tx").contextMenu({
menu: 'replace'
}, function (action, el, pos) {
update(action, el)
});
function update(action, el) {
var range = $("#tx").getSelection();
var textLength = $("#tx").val().length;
var firstPart = $("#tx").val().substring(0, range.start);
var secondPart = $("#tx").val().substring(range.start, textLength);
var lastIndexofSpaceInfirstPart = firstPart.lastIndexOf(" ");
var firstIndexofSpaceInSecondPart = secondPart.indexOf(" ");
var startOfWord = 0
var endOfWord = 0
if (lastIndexofSpaceInfirstPart < 0) {
// start of string
startOfWord = 0;
} else {
startOfWord = lastIndexofSpaceInfirstPart;
}
if (firstIndexofSpaceInSecondPart < 0) {
// end of textArea
endOfWord = textLength
} else {
endOfWord = firstIndexofSpaceInSecondPart + range.start;
}
var word = $.trim($("#tx").val().substring(startOfWord, endOfWord));
var replaceMent = $("#tx").val().substr(0, startOfWord)
+ action.toString()
+ $("#tx").val().substr(endOfWord, textLength);
alert(
"rangeStart: " + range.start +
"\n\nrangeEnd: " + range.end +
"\n\nrangeLength: " + range.length +
+"\n\nfirstPart: " + firstPart
+ "\n\n secondPart: " + secondPart
+ "\n\n lastIndexofSpaceInfirstPart: " + lastIndexofSpaceInfirstPart
+ "\n\n firstIndexofSpaceInSecondPart:" + firstIndexofSpaceInSecondPart
+ "\n\nWordStart: " + startOfWord
+ "\n\nEndofWord: " + endOfWord
+ "\n\nWord: '" + word + "'"
+ "\n\nNew Text: '" + replaceMent + "'"
);
}
});
Html
<textarea id="tx">
Some text
</textarea>
<ul id="replace" class="contextMenu">
<li class="edit">youwordhere1</li>
<li class="cut separator">youwordhere2</li>
<li class="copy">youwordhere3</li>
<li class="paste">youwordhere4</li>
<li class="delete">youwordhere5</li>
<li class="quit separator">youwordhere6</li>
</ul>
To detect a word under the mouse cursor rock solid reliable: Just wrap every word you want to detect in a separate container, span for example. It is not difficult to do with javascript. Just parse the words in a loop and create span element for every one, then set its innerHTML = word. Then you can read the click event target and it will give you the span with the word.
To show a context menu on the spot is a trivial task:
Create a div with your content menu and make it positiion:absolute and display:none. When you want to show it, set its top and left styles (for example) equal to the target span element offset from the parent container and make its style display = "box". You are all set ;)

Categories

Resources