Can OnClick do 2 things? - javascript

This is the html code...
<div id="video-embeds">
<div id="Div1">
<input id="Button1" type="button" value="►" onclick="switchVisible();" style="font-size: 40px; font-weight: bold; line-height: 2; background-color: #000; text-align: center; color: #fff; margin-bottom: 0px; z-index: 102; background: url('.get_post_meta(get_the_ID(), 'fifu_image_url', TRUE).') no-repeat; background-size: cover; position: relative; padding-bottom: 56.25%; padding-top: 0px; height: 0; margin-bottom: 0px; width: 100%; font-size: 120px; line-height: 5;"/>
</div>
<div id="Div2" class="video-embed" style="font-size: 40px; font-weight: bold; line-height: 2; background-color: #000; text-align: center; color: #fff; margin-bottom: 0px; z-index: 102;display:none;">'.
do_shortcode('[video_display]').'
</div>
</div>
This is the script...
<script type="text/javascript">
function switchVisible() {
if (document.getElementById('Div1')) {
if (document.getElementById('Div1').style.display == 'none') {
document.getElementById('Div1').style.display = 'block';
document.getElementById('Div2').style.display = 'none';
}
else {
document.getElementById('Div1').style.display = 'none';
document.getElementById('Div2').style.display = 'block';
}
}
}
</script>
I want to add url openning in new pop up window or new window also onclick input as
Something like...
https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode( get_permalink( get_the_ID() ) ); ?>
Is it possible?

The best way is to use addEventListener, and just forget about the onclick attribute altogether. Remove the onclick in your <button> code and add this to the script:
document.getElementById("Button1").addEventListener("click", (e) => {
/* write code for stuff button is supposed to do when clicked */
});
This way, you are separating your JavaScript from your HTML, resulting in nicer code. Instead of calling an anonymous function (e) => { ... } or function() { ... }, you can call functions by name, and you can do this repeatedly, if you want multiple functions to run when the button is clicked:
document.getElementById("Button1").addEventListener("click", functionName1);
document.getElementById("Button1").addEventListener("click", functionName2);
/* etc... */
With that code, both functionName1() and functionName2() will run when the button is clicked.
More info: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
And make sure the <script> tag is the last element inside the <body> tag, so that the script does not interrupt the loading of the page.

You can try bootstrap modal
example
OR
window.open('http://google.com');

Related

How to create a start screen for my Blackjack game in HTML

I am working on a beginner project and I have extreme trouble creating a simple start screen. I want to have a blank screen with a play button and a title. Pressing the play button should cause the header and button to disappear and the cards to be shown. However, when I press the play button I get this error:
Uncaught TypeError: GameLoop.start is not a function
at enterGame (blackjack.js:30:14)
at HTMLButtonElement.onclick (index.html:16:43)
I cannot figure out what this means as start is definitely a function in GameLoop. This is what I see now when I enter my game:
The dealer card and buttons show for some reason, unknown to me. Here is the code:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>cwd.gameloop.js</title>
<meta charset="UTF-8">
<meta name="viewport" content=""width=device-width, initial-scale="1.0">
<title>Black Jack</title>
<link rel="stylesheet" href="blackjack.css">
<script src="blackjack.js"></script>
<script src="gameloop.js"></script>
</head>
<body>
<div id="start-screen" class="screen" style="display:block">
<h1>Welcome to the Blackjack trainer!</h1>
<button onclick="enterGame()">Play</button>
</div>
<canvas id="canvas" style="display:none"></canvas>
<h2>Dealer: <span id="dealer-sum"></span></h2>
<div id="dealer-cards">
<img id="hidden" src="./Card images/card_back.png">
</div>
<h2>You: <span id="player-sum"></span></h2>
<div id="player-cards"></div>
<br>
<button id="hit">Hit</button>
<button id="stand":>Stand</button>
<button id="double":>Double</button>
<button id="surr":>Surrender</button>
<p id="results"></p>
</body>
</html>
blackjack.css:
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
color: white;
background-color: #225338;
}
#dealer-cards img {
height: 280px;
width: 200px;
margin: 1px;
}
#player-cards img {
height: 280px;
width: 200px;
margin: 1px;
}
#hit {
width: 100px;
height: 50px;
font-size: 20px;
}
#stand {
width: 100px;
height: 50px;
font-size: 20px;
}
#double {
width: 100px;
height: 50px;
font-size: 20px;
}
#surr {
width: 100px;
height: 50px;
font-size: 20px;
}
relevant parts of blackjack.js:
window.onload = function() {
}
window.onresize = function() {
GameLoop.onresize();
}
function enterGame() {
GameLoop.start();
}
gameloop.js:
class GameLoop {
constructor() {
this.fps = 60;
this.ctx = null;
this.cnv = null;
this.loop = null;
}
prepareCanvas() {
this.cnv = document.getElementById('canvas');
this.ctx = this.cnv.getContext('2d');
document.body.style.margin = 0;
document.body.style.padding = 0;
this.onresize();
}
onresize() {
if ( this.cnv ) {
this.cnv.width = window.innerWidth;
this.cnv.height = window.innerHeight;
this.resize();
}
}
start() {
this.toggleScreen('start-screen',false);
this.toggleScreen('canvas',true);
this.prepareCanvas();
this.init();
this.loop = setInterval(() => {
this.update();
this.render();
}, 1000/this.fps);
}
toggleScreen(id,toggle) {
let element = document.getElementById(id);
let display = ( toggle ) ? 'block' : 'none';
element.style.display = display;
}
I have been stuck on this for hours.
You have not implemented the following methods of your GameLoop class:
resize()
init()
update()
render()
You have instantiated the GameLoop class incorrectly. This is the way to do it properly:
const blackJackGame = new GameLoop()
blackJackGame.start();
Your toggleScreen() function is not a toggle function. It is a set function. You are passing the id of an element to this function with a true or false setting. A proper toggle function checks the state of the element and then flips it to the other state.
It is very difficult to understand how you want this code to work, so all that can be done is show you what is definitely not working with this code.
Finally, in your HTML, you have created a div called start-screen. It might be an idea to wrap the rest of your HTML in another div called game-screen. Then you can start by displaying the start screen and after the Enter button is pressed, you can hide the start screen and show the game screen.
Please note that I have created a CSS class called #game-screen so that the game screen is not visible at the beginning.
function enterGame() {
document.getElementById('start-screen').style.display = 'none';
document.getElementById('game-screen').style.display = 'block';
}
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
color: white;
background-color: #225338;
}
#game-screen {
display: none;
}
#dealer-cards img {
height: 280px;
width: 200px;
margin: 1px;
}
#player-cards img {
height: 280px;
width: 200px;
margin: 1px;
}
#hit {
width: 100px;
height: 50px;
font-size: 20px;
}
#stand {
width: 100px;
height: 50px;
font-size: 20px;
}
#double {
width: 100px;
height: 50px;
font-size: 20px;
}
#surr {
width: 100px;
height: 50px;
font-size: 20px;
}
<div id="start-screen" class="screen" style="display:block">
<h1>Welcome to the Blackjack trainer!</h1>
<button onclick="enterGame()">Play</button>
</div>
<div id="game-screen">
<canvas id="canvas" style="display:none"></canvas>
<h2>Dealer: <span id="dealer-sum"></span></h2>
<div id="dealer-cards">
<img id="hidden" src="https://source.unsplash.com/random/100x100/?card">
</div>
<h2>You: <span id="player-sum"></span></h2>
<div id="player-cards"></div>
<br>
<button id="hit">Hit</button>
<button id="stand" :>Stand</button>
<button id="double" :>Double</button>
<button id="surr" :>Surrender</button>
<p id="results"></p>
</div>

Event delegation from target to all inner elements when HTML is dinamically appended?

I have this basic HTML that represents a button, I want to attach a click event, but this button is appendend dinamically to the container through a an ajax function, so because this is not present initialy in the DOM, I'm attaching the event to the container in this way
document.querySelector('#container').addEventListener('click', (e) => {
var t = e.target.classList;
if( t.contains('button-outer') ) console.log(e.target);
});
#container {
width: 100%;
height: 100%;
position: relative;
text-align: center;
}
.button-outer {
padding: 15px;
background-color: orange;
display: inline-block;
margin: 0 auto;
text-align: center;
}
.button-inner{
font-weight: bold;
cursor: pointer;
font-size: 75px;
}
<div id="container">
<div class="button-outer">
<div class="button-inner">BUTTON</div>
</div>
</div>
This works, but obviously only when I'm clicking on on the padding part of the outer div. To fix this I have to change the if statement in a way that it will contains the inner part too, like this:
document.querySelector('#container').addEventListener('click', (e) => {
var t = e.target.classList;
if( t.contains('button-outer') || t.contains('button-inner')) console.log(e.target);
});
I think that this is a little uncovenient, because sometimes the inner part could have other classes, or could be an icon, a link, it is a little difficoult to create specific statements each time, so question is:
How can I propagate the event starting from outer to all inner elements when the button is dinamically appended?
You should attach your event handler when the button is created, in your ajax function.
But if you need to do it the way you are doing it, you can use closest(), it will traverse all of the target's parents until it finds your query.
document.querySelector('#container').addEventListener('click', (e) => {
var t = e.target;
if(t.closest('.button-outer')) console.log(e.target);
});
#container {
width: 100%;
height: 100%;
position: relative;
text-align: center;
}
.button-outer {
padding: 15px;
background-color: orange;
display: inline-block;
margin: 0 auto;
text-align: center;
}
.button-inner{
font-weight: bold;
cursor: pointer;
font-size: 75px;
}
<div id="container">
<div class="button-outer">
<div class="button-inner">BUTTON</div>
</div>
</div>

How can I optimize a popup Javascript code?

I'm just starting with Javascript and I made this popup code, and I was wondering if there's another code with the same result or a way of optimizing the Javascript.
The code must make the popup appear when one of the options is clicked and disappear when the click is somewhere else.
Popup code
var activePopup;
document.querySelectorAll('[hasPopup]').forEach((popupParent) => {
popupParent.addEventListener('click', e => {
if (popupParent != activePopup && activePopup != null) {
activePopup.querySelector('[popupContent]').style.display = 'none';
}
window.addEventListener('click', hasClicked => {
let isOnPopup = false;
hasClicked.path.forEach((event) => {
if (event == popupParent) {
isOnPopup = true;
}
})
if (isOnPopup == false){
popupParent.querySelector('[popupContent]').style.display = 'none';
}
})
popupParent.querySelector('[popupContent]').style.display = 'block';
activePopup = popupParent;
})
});
This will do all that you require, but in a much shorter form
puc=document.querySelectorAll("[popupContent]"); // popup divs ...
document.querySelector(".nav-bar__element").onclick=ev=>{
// in case the user clicked on the inner span and not the div:
const pel=[...ev.path].find(e=>e.hasAttribute&&e.hasAttribute("hasPopup"))
if (pel) {
const el=pel.querySelector("[popupContent]");
puc.forEach(d=>d.style.display=d===el?"block":"none")
}
}
body {
margin: 0;
font-family: sans-serif;
height: 100vh;
display: grid;
grid-template-columns: 25fr 75fr;
}
.small-icon {
width: 30px;
height: 30px;
}
[hasPopup] {
position: relative;
display: flex;
align-items: center;
justify-content: center;
margin: 30px;
padding: 20px;
border-radius: 10px;
border: 1px solid hsl(0, 0%, 40%);
}
[hasPopup]:hover {
cursor: pointer;
}
[popupContent] {
position: absolute;
cursor: auto;
padding: 20px;
border-radius: 10px;
border: 1px solid hsl(0, 0%, 40%);
left: 110%;
display: none;
}
<div class='nav-bar__element nav-bar__element--utils'>
<div class='utils__notifications' id='utilsNotifications' hasPopup>
<span>Notifications</span>
<div class="notifications-popup" popupContent>
<div>
notifications
</div>
</div>
</div>
<div class='utils__messages' id='utilsMessages' hasPopup>
<span>Messages</span>
<div class="messages-popup" popupContent>
<div>
messages
</div>
</div>
</div>
<div class='utils__settings' id='utilsMessages' hasPopup>
<span>Settings</span>
<div class="settings-popup" popupContent>
<div>
settings
</div>
</div>
</div>
<script type='text/javascript' src='script.js'></script>
</div>
If you are looking for a JS popup than check this:- https://www.gitto.tech/posts/simple-popup-box-using-html-css-and-javascript/
It worked for me this way:
HTML code
<div class="invalid-chars-alert-close-btn" onclick="document.getElementById('invalidChars-1').classList.toggle('active');">x</div>
JS: code inside if invalid characters written in my form then:
document.getElementById("invalidChars-1").classList.toggle("active");

Make the Modal Box Appear only Once in Tab Session

I am facing a problem with the modal box that I created.
Let me first put all of the code first.
var modal = document.getElementById("modal");
var close = document.getElementsByClassName("modal-close")[0];
if (modal.style.display == "block") {
sessionStorage.setItem("ModalSeen", "Seen")
}
if (window.performance) {
console.log("Window Performance works fine.")
}
if (performance.getEntriesByType('navigation')[0].type != 'navigate') { // Reload Happened
modal.style.display = "none";
sessionStorage.setItem("ModalSeen", "Seen");
} else {
modal.style.display = "block";
sessionStorage.setItem("ModalSeen", "Not Seen");
}
close.onclick = function() {
modal.style.display = "none";
sessionStorage.setItem("ModalSeen", "Seen");
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
sessionStorage.setItem("ModalSeen", "Seen");
}
}
if (sessionStorage.getItem("ModalSeen") == "Seen") {
modal.style.display = "none";
} else if (sessionStorage.getItem("ModalSeen") == "Not Seen") {
modal.style.display = "block";
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin-left: auto;
margin-right: auto;
margin-top: 2%;
padding: 20px;
border: 1px solid #888;
border-radius: 13px;
width: 33%;
}
.modal-close {
color: #aaaaaa;
float: right;
font-size: 30px;
font-weight: bold;
}
.modal-close:hover,
.modal-close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-img {
width: 20%;
display: block;
margin-left: 41%;
}
.modal-heading {
font-family: Noto Sans KR, sans-serif;
font-size: xx-large;
font-weight: bold;
color: #363636;
margin-left: 36.3%;
}
.modal-txt {
font-family: Noto Sans KR, sans-serif;
font-size: 17px;
color: #363636;
text-align: center;
width: 85%;
margin-left: 7.5%;
}
<div id="modal" class="modal">
<div class="modal-content">
<span class="modal-close">×</span>
<img class="modal-img" src="icons/Country - Error.png">
<p class="modal-heading">Warning</p>
<p class="modal-txt">Hey! This doesn't work outside of India.</p>
<p class="modal-txt">If you are outside India, you can continue to use the website, but you can't install the app.</p>
</div>
</div>
I want to display a modal box to the user when the user first opens the website. I don't want it to appear ever again, even if he refreshes the page or manipulates it. I only want it to appear when the user opens a new tab and goes to my website.
In the HTML and CSS code, I don't believe there is anything wrong with it.
In JavaScript, I have used SessionStorage (because that is more relevant than local storage in this case) and I put a key as "ModalSeen" and there are 2 values for it: "Seen" & "Not Seen". In the end, I have placed an if condition: If the value is Seen, the modal box should not appear again. If the value is Not Seen, the modal can appear again.
I tried a lot of things, but this was the best I could do.
Can you please help me to achieve this by making the modal open only once in the whole tab session? Thanks in Advance!
I think that you might need to use cookies for that

Customise button labels on JavaScript "confirm" dialog [duplicate]

This question already has answers here:
How to create a dialog with “Ok” and “Cancel” options
(17 answers)
Closed 7 years ago.
I have tried these code for displaying yes or no command as pop-up icon.But it is displaying ok and cancel button.If anybody can suggest me an idea would be helpful for my project.I have added my code below
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to block hour?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "NO";
}
document.forms[0].appendChild(confirm_value);
}
You have to create your own confirmBox,it is not possible to change the buttons in the dialog displayed by the confirm function.
see this example: http://jsfiddle.net/kevalbhatt18/tr6k43ca/
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// do nothing
});
EDIT
I created JavaScript confirmBox
Example: http://jsfiddle.net/kevalbhatt18/qwkzw3rg/1/
<div id="id_confrmdiv">confirmation
<button id="id_truebtn">Yes</button>
<button id="id_falsebtn">No</button>
</div>
<button onclick="doSomething()">submit</button>
Script:
<script>
function doSomething(){
document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line
document.getElementById('id_truebtn').onclick = function(){
//do your delete operation
alert('true');
};
document.getElementById('id_falsebtn').onclick = function(){
alert('false');
return false;
};
}
</script>
CSS:
body { font-family: sans-serif; }
#id_confrmdiv
{
display: none;
background-color: #eee;
border-radius: 5px;
border: 1px solid #aaa;
position: fixed;
width: 300px;
left: 50%;
margin-left: -150px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#id_confrmdiv .button {
background-color: #ccc;
display: inline-block;
border-radius: 3px;
border: 1px solid #aaa;
padding: 2px;
text-align: center;
width: 80px;
cursor: pointer;
}
#id_confrmdiv .button:hover
{
background-color: #ddd;
}
#confirmBox .message
{
text-align: left;
margin-bottom: 8px;
}
The browsers' API doesn't support custom buttons. OK and Cancel are the only buttons you can get.
If you want custom popup buttons you can use a library to make the popup like alertify.
according to me you cannot change the standard javascript pop-up button labels. In case you want to do so, you can use the jquery-ui or you can create your own custom pop-up and check for the button clicks. This is a better way rather than using the default pop-up as the UI varies from browser to browser.

Categories