I'm still learning my way through all this stuff but what I was trying to do now was create a Tic-Tac-Toe game out of HTML, CSS & Javascript. However no matter what I try my onClick events won't run correctly. I just want the game to respond to the click by the player, send the identity of the tile clicked to the function so that it knows which one to change, and then change the tile's image (to either a nought or a cross).
I'm thinking that the best way to do this is have the onClick pass a different argument through depending on the id of the tile clicked but it's telling me that placeTile() isn't defined and besides there has to be an easier way to do it than the cocktail that I've conceived. Thanks for your help in advance! :)
The HTML:
<html>
<head>
<title> Tic-Tac-Toe </title>
<link type='text/css' rel='stylesheet' href='Tic-Tac-Toe.css'/>
<script type='text/javascript' src='JQuery/jquery-1.11.1.js'></script>
<script type='text/javascript' src='Tic-Tac-Toe.js'></script>
</head>
<body>
<div id='game'>
<div id='container'>
<div id='board'>
<div class='emptyTile' id='NW' onClick='placeTile("NW")'></div>
<div class='emptyTile' id='N' onClick='placeTile("N")'></div>
<div class='emptyTile' id='NE' onClick='placeTile("NE")'></div>
<div class='emptyTile' id='W' onClick='placeTile("W")'></div>
<div class='emptyTile' id='C' onClick='placeTile("C")'></div>
<div class='emptyTile' id='E' onClick='placeTile("E")'></div>
<div class='emptyTile' id='SW' onClick='placeTile("SW")'></div>
<div class='emptyTile' id='S' onClick='placeTile("S")'></div>
<div class='emptyTile' id='SE' onClick='placeTile("SE")'></div>
</div>
</div>
<div id='scores'>
<div class='score' id='Score1'> Player 1: <br/> <span id='pOne' class='num'>0</span></div>
<div class='score' id='Score2'> Player 2: <br/> <span id='pTwo' class='num'>0</span></div>
</div>
</div>
</body>
</html>
The Javascript Function:
function placeTile(a){
var tile = document.getElementById(a);
if (currentPlayer == 0) {
tile.removeClass('emptyTile');
tile.addClass('cross');
currentPlayer = 1;
} else {
tile.removeClass('emptyTile');
tile.addClass('nought');
currentPlayer = 0;
}
}
So as you can see I'm doing this in a roundabout way, but the onclick event is supposed to pass the id of the div to the function, which is then used to make all the necessary changes to that div only and also swap the current player. But it is very messy and I;m sure I could clean it up somehow if I could just figure out how to make one javascript function react differently depending on what div is clicked...
Oh I love code but I also hate it too. It's addictive really.
You've included jQuery so use the click event as per this JSFiddle.
http://jsfiddle.net/Delorian/3f2tvabo/
$('.emptyTile').click(function () {
if (currentPlayer == 0) {
$(this).removeClass('emptyTile');
$(this).addClass('cross');
currentPlayer = 1;
} else {
$(this).removeClass('emptyTile');
$(this).addClass('nought');
currentPlayer = 0;
}});
You won't need anything on the HTML elements apart from the class to indicate a tile.
You can take your second bloc of js code, Javascript function, and place it in a different class. then call it. Say for example you placed you code in a file called onclick.js then you'll call it in this form:
<script type="text/javascript" src="onclick.js"></script>
and if you placed in a folder, say for example it's called myFolder, then you'll call it with:
<script type="text/javascript" src="myFolder/onclick.js"></script>
I hope that helps.
First what does placeTile really need? Because it is being called from a DOM event drop the notion that you need to give it a string in the first place. For example:
function placeTile(tile) {
tile.removeClass('emptyTile');
tile.addClass(['nought', 'cross'][currentPlayer]);
currentPlayer = (currentPlayer + 1) % 2;
}
Now use event delegation. Set a click handler on the parent element and then look at the events target property to get the element that was actually clicked.
Live: http://jsbin.com/rahaba/1/edit?js,output
var board = document.getElementById('board');
board.addEventListener('click', function(e) {
if (e.target === e.currentTarget) {
return; // This is the parent div, we only want the children
}
if (e.target.tagName === 'DIV') {
e.stopPropagation();
placeTile(e.target);
}
});
and in jQuery:
// Notice the extra 'div' selector.
$('#board').on('click', 'div', function() {
placeTile(this);
});
Related
This is my code:
<div class="titfx">
<div class="clk1">CLICKME</div>
</div>
<div class="here" style="display:none;">info for here</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('.clk1').on("click", function(event) {
//first code
var here = $(this).parent(".titfx").next(".here");
here.toggle();
//second code
if (!here.is(event.target) && here.has(event.target).length === 0) {
here.hide();
}
});
});
</script>
What the first part of javascript code does: When the word "CLICKME" is clicked, then the hidden div with text "info for here" shows.
What the second part of javascript code should do: When any part of the screen that is not class="here" is clicked on, then the text "info for here" should hide. The second part of my code is unable to achieve that. I'm not sure what I'm doing wrong. Please help me fix this issue.
you need to bind two event listeners to achieve this, one for the "clk1" element, and one for the whole page.
when fires document click event, just hide the text,
when fires ".clk1" click element, you need to stop propagation first and then write the toggle behaviour.
this is my solution
$(document).ready(function() {
$('.clk1').on("click", function(event) {
//first code
event.stopPropagation();
$(".here").toggle();
});
//second code
$(document).on("click", function(event){
$(".here").hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titfx">
<div class="clk1">CLICKME</div>
</div>
<div class="here" style="display:none;">info for here</div>
Here is a potential solution. The first click binding works for the toggle logic. However, for your second scenario, you said you want it to close them if they click any where on the page, other than the two areas. In that regard, you are concerned with the click events for the body, not just the two areas.
The second logic binds to the body, and checks to see if the clicked element is a child of the .clk1 or the .here. If it is not a child of either one, it will hide the .here.
The css was added to force the page size to be larger than just the html provided so you could actually click on something not them, :)
$(document).ready(function() {
$('.clk1').on("click", function(event) {
var here = $(this).parent(".titfx").next(".here");
here.toggle();
});
$(document.body).on('click', function(event){
var clickedElement = $(event.target);
if (!clickedElement.closest('.clk1').length
&& !clickedElement.closest('.here').length) {
$('.here').hide();
}
});
});
body {
min-width: 800px;
min-height: 600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titfx">
<div class="clk1">CLICKME</div>
</div>
<div class="here" style="display:none;">info for here</div>
var testbutton = document.getElementById("testbutton");
var content = document.getElementById("content");
testbutton.onclick = function () {
html2canvas(content, {
"onrendered": function(canvas) {
document.body.appendChild(canvas);
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<p>
<a id="testbutton" href="javascript:void(0);">test</a>
</p>
<div id="content">
<div class="element-1">1. Is visible</div>
<div class="element-2" data-html2canvas-ignore="true">2. No visible</div>
<div class="element-3">3. Is visible</div>
</div>
Is there a way to actually remove that element so that the resulting rendered image doesn’t leave that empty space?
Are you using any Framework? If yes, your framework might have some html functionality or attribute to do this.
For example in Angular you would manage it with*ngIf .
It will help you to delete the empty element from your DOM
I created a simple event script, which changes the image when clicked on the button. But unfortunately not changing, please help.
Error: I am not getting any error message also , just it was not changing the image.
<html>
<head>
<title>Events Practise</title>
<style>
#imtest{
width:100px;
height:150px;
}
</style>
</head>
<body>
<h4> This a practise page of Events and event handlers </h4>
<p> Hi this the practise page that changes the Html and Css contents in the page by Using the JavaScript </p>
<img id="imtest" src="marni.jpg" alt="Image corrupted">
<button onclick="eventtest()">Change Image</button>
<script>
function eventtest()
{
var imt = document.getElementById("imtest");
imt.onclick = change;
}
function change()
{
var imtchng = document.getElementById("imtest");
imtchng.src = "marni1.png";
}
</script>
</body>
I created a simple event script , which changes the image when clicked
on the button
No you've created a script which set's a click handler on the image when the button is clicked and after that when the image is changed it will change.
If you want to change the image directly by clicking just set the click handler on it.
In the imt.onclick = change line you are forgetting the parentheses after the change. Replace it with change()
<script>
function eventtest()
{
change();
}
function change()
{
var imtchng = document.getElementById("imtest");
imtchng.src = "marni1.png";
}
</script>
or
<button onclick="change()">Change Image</button>
I have the following function:
$('.card1').click(function(){
// ...
});
I want to avoid repetition and would want this function to execute for any of the following selectors: $('.card1'), $('.card2'), $('.card3'), $('.card4'), $('.card5'), $('.card6'), $('.card7'), $('.card8')
Maybe have an if condition, where if this is clicked or that, but not sure.
You should convert those classes to id or ad id for those tags then easily you can find which tag is clicked you can see example here
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var cardnumber = ["#card1", "#card2", "#card3", "#card4", "#card5"];
$("#card1, #card2, #card3, #card4, #card5").click(function() {
var y = cardnumber.indexOf("#" + this.id);
alert(y);
});
});
</script>
</head>
<body>
<p id="card1">Click me!</p>
<p id="card2">Click me!</p>
<p id="card3">Click me!</p>
<p id="card4">Click me!</p>
<p id="card5">Click me!</p>
</body>
</html>
Either use a common class for all the elements :
$('.card')
or make a group selector:
$('.card1, .card2....n')
You can try to match elements that have class 'card' starts with 'card', like this $("div[class^='card'],div[class*=' card']").click(function(){...});
Try using Attribute Starts With Selector [name^="value"]
$("[class^=card]").click(function() {})
better to introduce a new css class for the click
CSS
/*all cards*/
.card {...}
/*personalized cards*/
.card1 {...}
.card2 {...}
.....ect
javascript
$('.card').click(function(){
// ...
});
html
<div class="card card1">card1</div>
<div class="card card2">card2</div>
<div class="card card3">card3</div>
<div class="card card4">card4</div>
Hope that makes sense to you or at least gives you ideas.
You would then made the specify class --> ids depending on whether they are repeated or not.
<div id="card1" class="card">card1</div>
<div id="card2" class="card>card2</div>
<div id="card3" class="card">card3</div>
<div id="card4" class="card">card4</div>
you would then need to change the CSS to accommodate this change.
Then you would get the card number by asking for the Id in the javascript.
javascript
$('.card').click(function(){
var $this = $("this");
var cardId = $this.attr("id");
if(cardid == "card1") {
//your code
} else if(cardid == "card2") {
//your code
}
});
I have a HTML-page with a lot of different DIVs in it and I want to print out the the DIV that the user has clicked in and hide all the rest.
Can someone tell me how to do this in Javascript please?
<html>
<head>
<title>Print Demo</title>
<script type="text/javascript">
<!-- MY JAVASCRIPT FUNCITON -->
</script>
</head>
<body>
<div id="div1">
Print the page with this div
</div>
<div id="div2">
Print the page with this div
</div>
<div id="div3">
Print the page with this div
</div>
</body>
</html>
This is just to extend pimvdb's answer.
jQuery:
$("a").on("click", function(){
$("div").hide();
$(this).parent().show();
});
Or as suggested:
$("a").on("click", function(){
$("div").hide();
$(this).closest("div").show();
});
Hiding an element means setting it's style.display property to "none". Showing means setting it to "block" for a div element.
In combination with getElementsByTagName, you could accomplish this: http://jsfiddle.net/b9cgM/.
function show(elem) {
// hide all divs initially
var allDivs = document.getElementsByTagName("div");
for(var i = 0; i < allDivs.length; i++) {
allDivs[i].style.display = "none";
}
// show the appropriate div
elem.parentNode.style.display = "block"; // parent of the <a> is the <div> to show
}
You could bind the event like <a href="#" onclick="show(this); return false;">. The element (this) is then passed to show.
As a side note, libraries such as jQuery make this even easier; you might want to check that out (though I don't recommend including it if the only use case would be this).
sorry, there is only window.print() for printing in js, which means you can only print the entire window. if you want some to be able to print your document, make it printable using CSS.
for instance, maybe you want your navigation to disappear for printing, but leave the title of your page there and the name of your web site and maybe a page URL (sometimes browsers like firefox cut those off if they are too long). and sometimes some sites take away the browser controls and make the mistake of leaving you with no print button - and it's an online purchasing site... it's happened before.
<style type="text/css">
#media print {
.boxGreen {
padding:10px;
border-color:green;
border-style:dashed;
border-width:thin;
}
}
#media screen {
.boxGreen {
padding:10px;
border-color:green;
border-style:dashed;
border-width:thin;
}
}
</style>
you CAN do an onclick="switchtodiv('someid')" and then after the divs do this:
<div onclick="switchtodiv('span1')">ClickMe<span id="span1">some content</span></div>
<div onclick="switchtodiv('span2')">ClickMe<span id="span2">some content</span></div>
<div onclick="switchtodiv('span3')">ClickMe<span id="span3">some content</span></div>
<!--you can generate these divs using a for statement...-->
<script type="text/javascript">
//switchdiv allows only 1 div tobe
function switchdiv(id) {
var ids=new Array('span1','span2','span3');
var i;
for (i=0; i < ids.length; i++) {
if (ids[i] == id) {
document.getElementById(ids[i]).style.visibility='visible';
document.getElementById(ids[i]).style.display='block';
} else {
document.getElementById(ids[i]).style.visibility='hidden';
document.getElementById(ids[i]).style.display='none';
}
}
}
</script>
You could use a javascript function like document.getElementById(id) to hide the two other divs
So in your function you could just use
function hide1() {
document.getElementById(div2).style.display = "none";
document.getElementById(div3).style.display = "none";
}