just started learning Javascript and it's pretty hard. But I followed one tutorial and did as he told in his video, but still my result is not what I expected and what he got in his video. I wonder why is that and how I can fix that?
I want to get the box to appear out of nowhere with the text in it and follow the cursor for as long as it is inside the marked territory (LABEL- box in HTML).
Here's the code:
$("#rulesInfo").mouseover(function(e) {
var hovertext = "Info for the block will come here.";
$("#hoverdiv").text(hovertext).show();
$("#hoverdiv").css("top", e.clientY+10).css("left", e.clientX+10);
}).mouseout(function() {
$("#hoverdiv").hide();
});
#hoverdiv {
display: none;
position: absolute;
font-size: 12px;
background-color: #161616;
color: #fff;
border: 1px solid red;
padding: 8px;
border-radius: 5px;
}
<FORM>
<DIV ID="bottom">
<P>
<INPUT TYPE="checkbox" NAME="checkedRules" VALUE="yes" REQUIRED /><LABEL FOR="checkedRules" ID="rulesInfo">I have read the Rules and Conditions for the trip.</LABEL>
</P>
</DIV>
</FORM>
<DIV ID="hoverdiv"></DIV>
<SCRIPT TYPE="text/javascript" SRC="jquery.js"></SCRIPT>
<SCRIPT TYPE="text/javascript" SRC="app.js"></SCRIPT>
What you would like to do is user the mousemove event which fires on every mouse move of the object. mouseover only occurs when the mouse first moves over the object.
see here:
$("#rulesInfo").mousemove(function(e) {
var hovertext = "Info for the block will come here.";
$("#hoverdiv").text(hovertext).show();
$("#hoverdiv").css("top", e.clientY+10).css("left", e.clientX+10);
}).mouseout(function() {
$("#hoverdiv").hide();
});
http://jsfiddle.net/mzwj26a7/
Related
I'm new to coding, I've learned the very basics of html/css/js/java, at least I thought I had, until I went to make a simple game.
I made a simple choose your own adventure game that worked, as each choice just went to a new page.
Then, I thought I'd make it a bit more complex, so I want to have the user enter their name, and store that to show next to the player's stats.
I've got a dropdown box with 4 choices for characters.I want to have Strength/Mana/Lives stats and have the player's choice of character to be able to adjust these stats accordingly before the game starts i.e. Male Warrior would have 2 extra Strength, Female Mage 2 extra mana etc.
Then, I'd like an image based on their character choice displayed next to their stats, so that the game can begin.
So far, I've been pulling my hair out in great clumps and have tried many different methods but so far, I've only got to the stage where I place the page with user input into an iframe. I can get to reflect their choices with text, but I can't get an image to load on submit. Ideally I'd like a permanent box in the top corner of the iframe, and have the statistics variables passed into the stats shown alongside the character's image.
I'd really really appreciate any help here, especially if it can be solved using HTML/CSS/JS as I'm not too familiar with JQuery, and would like to keep it as simple as possible really.
I've gone through as many q's and a's as I can to find relevant help, but I'm mainly finding answers for PHP or other languages.
I must apologise in advance for my waffling above, and sloppy coding. (I seriously thought this would be easy heh).
I'm unsure if my code so far will help, but I'll just paste it below anyway.
HTML for the UI page is:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Character Selection</title>
<link rel="stylesheet" href="css/style2.css">
<style>
img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div id='gamestitle'>
<p>
<img src = "GAMETITLE.jpg"
alt = "Steve's Perilous Capers"/>
</p>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLable' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
<div>
</div>
<div>
<form>
Select your Hero please:
<select id="mySelect">
<option>Male Warrior</option>
<option>Male Mage</option>
<option>Female Warrior</option>
<option>Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<script src="js/index.js"></script>
<script>
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
</script>
<p id="demo"></p>
</body>
</html>
The CSS is:
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide { display: none;}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
The JS file: (I've tried using icons and background image but I couldn't get them to show)
// the function which handles the input field logic
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your Hero is: ' + nameField;
//alert(nameField);
}
}
function getOption() {
var obj = document.getElementById("mySelect");
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
}
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dd");
image.src = dropd.value;
};
// use an eventlistener for the click event
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
var subButtonTwo = document.getElementById('subButtonTwo');
subButtonTwo.addEventListener('click', getOption, false);
$(function () {
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
_renderItem: function (ul, item) {
var li = $("<li>"),
wrapper = $("<div>", {text: item.label});
if (item.disabled) {
li.addClass("ui-state-disabled");
}
$("<span>", {
style: item.element.attr("option-style"),
"class": "ui-icon " + item.element.attr("data-class")
})
.appendTo(wrapper);
return li.append(wrapper).appendTo(ul);
}
});
$("#mySelect")
.iconselectmenu()
.iconselectmenu("menuWidget")
.addClass("ui-menu-icons avatar");
});
/*
function getcurrentChoice() {
var characterSelection = ['MaleWarrior'], ['MaleMage'], ['FemaleWarrior'], ['FemaleMage'];
var currentChoice = document.getElementById('currentChoice').value;
var resultChoice = document.getElementById('resultChoice');
var subButtons = document.getElementById('subButtons');
subButtons.addEventListener('click', getcurrentChoice, false);
}
*/
Sorry for the messy coding, it's not helped that I've tried so many workarounds for each problem I've encountered that I've lost track of what is and isn't working.
I'm pretty sure this is out of control by now, and a waste of your time, but I'm so confused. I'm sure i'm over complicating the matter.
Thanks in advance again,
Steve.
Check this:
https://jsfiddle.net/digitalrevenge/q9z1x6vv/
I've added an img src and made some changes to your JS.
I'm not sure if it does exactly what you want but there's no harm in giving it a try ;)
I am not sure how to do this in Javascript, but I have achieved it with jQuery, maybe you can adapt it to Javascript if you like.
Basically...
Give each option a value
On selection, or change, empty div#change_this, and check for the value
If value = # then add html code to div#change_this
You can change the image/add in the stats, I just used some filler.
You will also need to add css and all that, if you have any specific questions about that, please let me know.
Functionality is there though.
Best,
Levi
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide {
display: none;
}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
<div>
<div id='gamestitle'>
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLabel' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p>
</div>
</div>
<div>
<form>
Select your Hero please:
<select name="hero_type" id="mySelect">
<option value="0">Male Warrior</option>
<option value="1">Male Mage</option>
<option value="2">Female Warrior</option>
<option value="3">Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<div id="change_this">
<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select[name="hero_type"]').click(function() {
$('#change_this').empty();
if ($('select[name="hero_type"]').val() == "0"){
$('#change_this').append('<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "1"){
$('#change_this').append('<p>Yayyy, Male Mage.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "2"){
$('#change_this').append('<p>Yayyy, Female Warrior</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "3"){
$('#change_this').append('<p>Yayyy, Female Mage</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
})
});
</script>
The src attribute of an image tag points to the location of the image file to use.
You should be somewhat aware of this as your code contains:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
To change the image, simply change the src attribute to point to the location of the new image.
The source of an image tag can be accessed and changed via:
document.getElementById("imageId").src="fileToUse";
This means you need to add an id to your image tag as so:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers" id="imageId"/>
In your case, you want to get the image src from a select field. This means you need to tie the image file locations to your select form as values.
<select id="mySelect">
<option value="location-of-this-image.png">Male Warrior</option>
<option value="location-of-this-image.png">Male Mage</option>
<option value="location-of-this-image.png">Female Warrior</option>
<option value="location-of-this-image.png">Female Mage</option>
</select>
To use these values and assign them to the image src:
document.getElementById("imageId").src=document.getElementById("mySelect").value;
If you correctly id your image and select form, give the select form proper values, and put the above line of code in the function you call when choosing and image, your image should change.
Important Note
JQuery is a JavaScript library and isn't part of the base language. To use JQuery, you must import it in your html code. You seem to be using JQuery functions, but I don't see where you imported JQuery. This may be causing you problems/breaking your code.
If you do have JQuery imported, the above code can be rewritten using JQuery rather than vanilla JavaScript and it'll look a lot cleaner.
I use a plug in to handmade a placeholder for conteditable div.
showed in demo below. If user puts in some text then click the post button, the placeholder disappeared.I wondered how to get the placeholder back after posting.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id="topic_content_input" contenteditable="true" autocomplete="off" spellcheck="false" data-placeholder="placeholder text" ></div>
<button id="post">Post topic</button>
<style>
#topic_content_input[data-placeholder]:not([data-div-placeholder-content]):before {
content: attr(data-placeholder);
float: left;
cursor:text;
margin-left: 2px;
color: rgba(134,134,134,0.6);
}
#topic_content_input{
width:521px;
padding: 10px;
border: 1px solid orange;
}
#topic_content_input:focus{
outline-style:solid;
outline-color:orange;
outline-width:0px;
line-height:normal;
}
</style>
<script>
(function ($) {
$(document).on('change keydown keypress input', '#topic_content_input[data-placeholder]', function() {
if (this.textContent) {
this.dataset.divPlaceholderContent = 'true';
}
else {
delete(this.dataset.divPlaceholderContent);
}
});
})(jQuery);
</script>
<script>
$("#post").click(function(){
$("#topic_content_input").text("");
var obj=$("#topic_content_input");
// $("#topic_content_input").add(obj.dataset.divPlaceholderContent); //my attempt, not working
})
</script>
In the CSS, rather than having #topic_content_input[data-placeholder]:not([data-div-placeholder-content]):before, you can instead put in #topic_content_input:empty:before, which will put in the placeholder whenever the div is empty, as seen in this jsfiddle.
$("#topic_content_input").add(obj.dataset.divPlaceholderContent);
why ".add" ?
you shoul use:
obj.val(obj.dataset.divPlaceholderContent)
or
obj.attr('placeholder', obj.dataset.divPlaceholderContent)
I am new all around HTML and JavaScript. Now I am trying to build a simple program that get input from the command line by the user and print it on the big console window. Now when I insert a simple text it does not print nothing into the box. Is there a special object should I use?
this is my code:
</head>
<body>
<img src="img/Mellanox_logo.jpg" alt="logo" align="middle">
<h1>Menu</h1>
<div id="container1" >
<div id="console" >
<p>
<script>
function showVal(){
var tmp = document.lineform.command_line.value;
document.getElementsByName('command_line').value = tmp;
}
</script>
</p>
</div>
<div >
<form id="form1" name="lineform" >
<input id="commandline" type="text" name="command_line" placeholder="Command line" onclick="showVal()" >
</form>
</div>
</div>
</body>
</html>
this is the css:
h1{
color: black;
text-align: left;
}
p{
color: black;
text-align: left;
font-size: 20px;
}
#container1{
width:1300px ;
}
#form1{
width:1300px ;
}
#console{
border:5px solid dodgerblue;
background-color: white;
height: 650px ;
padding-left: 5px;
margin-bottom: 5px;
position: relative;
width: inherit;
}
#commandline{
width: inherit;
border: 5px solid dodgerblue;
height: 30px;
padding-left: 5px;
font-size: 18px;
position: absolute;
}
this is how the command line and the window looks like:
1.- For this case i think you should be using getElementById instead of getElementsByName.
2.- I'd recommend not using a form, but instead have the input in the div's "root".
3.- A text input doesnt have a onclick (or at least it doesn't do what you want it to do)
4.- Add a button type input that executes the code through onclick="blabla();"
5.- i'd recommend putting your script at the end of the page since it works with the DOM and you're not using JQuery.
6.- add an id to the <p> element inside of the console <div>
<body>
<h1>Menu</h1>
<div id="container1">
<div id="console">
<p id="console_content">
</p>
</div>
<div>
<input id="commandline" type="text" name="command_line" placeholder="Command line">
<input id="commandButton" type="button" name="command_button" value="confirm" onclick="showVal();">
</div>
</div>
</body>
7.- new script:
<script>
function showVal() {
var tmp = document.getElementById("commandline").value;
document.getElementById('console_content').innerHTML += (tmp + "<br/>");
}
</script>
Here's a JFiddle so you can see it works:
https://jsfiddle.net/bLehLrum/
The function you are using returns an HTMLCollection, you need to the following:
Change,
document.getElementsByName('command_line').value = tmp;
To
document.getElementsByName('command_line')[0].value = tmp;
This gets the first element in the array, notice how there is an s at the end of getElements which suggests plural. This should help you in the future.
Reading Material
getElementsByName
Exdending Script47 answer, The problem is you are taking the value from input field and setting the same value again to it, That's why you are seeing any change/affect.
If by the box you mean the console, you should change your function with this
function showVal(){
// get the value of the input
var tmp = document.getElementById('commandline').value;
// add to the innerHTML of the console the tmp value
document.getElementById('console').innerHTML += "<p>"+tmp+"</p>";
}
document.getElementById
Your code try to reassign the value of command_line with the same value.
document.lineform.command_line.value could be the same as document.getElementsByName('command_line')[0]
<html>
<script language="javascript">
document.onmousemove=function(evt) {
evt = (evt || event);
document.getElementById('x').value = evt.clientX;
document.getElementById('y').value = evt.clientY;
document.getElementById('a').style.left = evt.clientX;
document.getElementById('a').style.top = evt.clientY;
}
$('.test').disableSelection();?
</script>
<body style="cursor: none;">
<input type="text" id="x"></input><br>
<input type="text" id="y"></input>
<div id="a" style="height: 3px; width: 3px; background-color: green; border-radius: 3px; position: absolute;"></div>
<div id="b" class="test" style="position: absolute; top: 0px; left: 0px; height: 100%; width: 100%;"></div>
</body>
</html>
This is the code I'm using. Now, if you try to use this code in your browser (I use Google Chrome or Firefox), you will notice that the green dot isn't following the cursor coordinates.
The dot will only follow the cursor if you remove all the other javascript code except for the ones you use to locate the cursor and to place the dot.
I have tried to locate the cursor with many other code and I also tried to use this code in combination with other javascript code but every time I tried, it doesn't work with other Javascript code in the file.
Then I tried to seperate the Javascript code in to different files:
<script language="javascript" src="loccur.js"></script>
<script language="javascript" src="disabletext.js"></script>
and it gave the same result.
I hope someone can help me to use this cursor-location-code or a similar one in combination with other javascript code.
Works fine for me in chrome if you remove the '?' at the end of line 10
TOP and LEFT require units:
document.getElementById('a').style.left = evt.clientX + 'px';
this one may be a little bit of a long one.
I have a form that takes a picture upload that I have customized with CSS to appear as a box. I would like it so that when the user clicks the box and are prompted to upload a picture, they can choose one and have it appear in the box (where the box will lengthen to fit the picture...the picture itself will be resized to fit the width, i have this part handled).
I am trying to make this happen with javascript, ajax, etc...:
I am including these scripts:
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script type="text/javascript" src="/js/script.js"></script>
as well as the code found here:
http://homesconnect.me/js/jquery.form.js
script.js contains:
function validate_picture(form_data, form) {
var form = form[0];
if ( ! form.picture.value)
return false;
}
function show_picture_loader() {
$('.add_picture_label').hide().before('<img src="/images/loader.gif" class="loader"/>');
}
function hide_picture_loader() {
$('.loader').remove();
$('.add_picture_label').show();
}
function show_error_message(form_obj, message) {
$('.error').remove();
if(message != '')
{
form_obj.before('<div class="notification_msg error">' + message + '</div>');
$('html,body').animate({scrollTop: form_obj.parent().offset().top});
}
}
I also have the live script in the page itself written as so:
<script>
$(document).ready(function(){
$('.upload_picture_form').ajaxForm({
dataType: 'json', beforeSubmit: show_picture_loader, success: function(data) {
$('.pictures').prepend('<div class="profile_picture"><div class="delete_picture"><span></span></div><img src="' + data.image + '" /></div>');
$('form.account_form').prepend('<input type="hidden" name="image[]" value="' + data.image + '" />');
hide_picture_loader();
}
});
$('input.upload_picture_file_input').change(function(e) {
$('.upload_picture_form').submit();
});
$('.delete_picture span').live('click', function(e) {
$(this).closest('.profile_picture').fadeOut();
$.get('delete_picture', {image: $(this).closest('.profile_picture').find('img').prop('src')});
});
});
</script>
The form code is as so:
<div class="pictures add_pictures">
<div class="add_picture">
<div class="upload_picture">
<form action="upload.php" method="POST" enctype="multipart/form-data" name="upload_picture_form" class="upload_picture_form">
<span class="add_picture_label">+ Add a Profile Picture</span>
<input type="file" name="upload_picture_fileinput" class="upload_picture_file_input"/>
<input type="hidden" name="MAX_FILE_SIZE" value="100000"/>
<br><br><br><br><br><br><br>
<input type="submit" id="submit" value="Upload" />
</form>
</div>
</div>
</div>
Upload.php takes the image uploaded and saves it in a directory on my server, as well as saving its filename in a mysql directory. This works fine. However, the javascript I have included are not making the image appear in the box, and hence I am not able to delete it or anything either.
Here's the relevant CSS if it matters:
.content .pictures {
padding: 5px;
background: #fff;
width: 350px;
float: right;
box-shadow: 0 1px 10px rgba(0,0,0,.2);
}
.content .pictures .profile_picture img {
margin: 0;
padding: 0;
width: 350px;
}
.content .pictures .profile_picture {
position: relative;
}
.content .pictures .profile_picture .delete_picture {
position: absolute;
right: 0;
top: 0;
display: none;
}
.content .pictures .profile_picture .delete_picture span {
padding: 0;
font: bold 12px/normal 'Helvetica', 'Arial', sans-serif;
color: #444;
cursor: pointer;
background: url(/images/close.png) no-repeat;
width: 30px;
height: 29px;
display: block;
}
.content .pictures .profile_picture:hover > .delete_picture {
display: block;
}
If you feel like you see a problem or can help I would be very appreciative. I know this one is a doozy ha. Thanks.
p.s. also is there a way that I can remove the "update" button, and have it so that the image is uploaded automatically when the it is chosen by the user (as opposed to having them hit a button to do so)?
EDIT: I may have misunderstood the question. What I interpreted was an effect like that of Newgrounds.com's text boxes, which have a picture inside the text boxes, a neat aesthetic. If I have misinterpreted the question, I apologize
in css, you can put
try this:
textarea#image { background-image:url('image.jpg'); width:600; height:400 }
in this simple css example, assuming you named your input "<textarea id="image"></textarea>", the document puts a background image inside the element.
Because of jQuery's CSS affinity, you might be able to achieve the same result using just jQuery.