Close button doesn't work on many Android devices - javascript

This is my code:
function setToTop(t) {
var n = 0;
$(".box").each(function(t, o) {
var e = Number.parseInt($(o).css("z-index"));
e = Number.isNaN(e) ? 0 : e, n = Math.max(n, e)
}), t.css({
zIndex: n + 1
})
}
$(function() {
$(document).mouseleave(function() {
$(document).trigger("mouseup")
}), $(".box").draggable({
helper: "original",
containment: "body",
drag: function(t, n) {
n.offset.left < 0 && (n.position.left = n.position.left - n.offset.left)
},
stop: function(t, n) {},
start: function(t, n) {
setToTop(n.helper)
}
})
}), $(".box span").click(function() {
$(this).parents(".box").css("display", "none")
});
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
font-size: 50px;
font-family: Arial;
background-color: rgb(220, 220, 220);
}
.box {
background-color: yellow;
color: black;
padding: 20px;
display: block;
position: absolute;
border: 2px black;
cursor: all-scroll;
border: 1px solid black;
}
.box:nth-child(1) {
left: 20%;
top: 10%;
}
.box:nth-child(2) {
left: 10%;
top: 15%;
}
.box:nth-child(3) {
left: 25%;
top: 30%;
}
.box:nth-child(4) {
left: 30%;
top: 20%;
}
.box span {
background-color: red;
color: white;
position: absolute;
top: -40px;
right: -40px;
padding: 10px;
cursor: pointer;
border: 1px solid black;
}
<div class="box">Hello <span>✕</span></div>
<div class="box">Love <span>✕</span></div>
<div class="box">Freedom <span>✕</span></div>
<div class="box">Peace <span>✕</span></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js" integrity="sha256-hlKLmzaRlE8SCJC1Kw8zoUbU8BxA+8kR3gseuKfMjxA=" crossorigin="anonymous"></script>
<script src="https://raw.githubusercontent.com/furf/jquery-ui-touch-punch/master/jquery.ui.touch-punch.min.js"></script>
The function is:
to have draggable boxes
the currently dragged box gets set on top
closing a box is possible with the ✕ button
Unfortunately, the ✕ button doesn't work on many touch devices. My research has shown that it works well on Apple devices, but pretty bad on many Android devices.
Has anyone an idea to fix that? Also, does anyone have an idea to optimize the code?
Would be very thankful for help! <3

Consider the following.
$(function() {
function setToTop(t) {
var n = $(".box").length;
$(".box").each(function(i, el) {
if (!isNaN($(el).css("z-index"))) {
n = parseInt($(el).css("z-index"));
}
});
t.css("z-index", n + 1);
return true;
}
$(document).mouseleave(function() {
$(document).trigger("mouseup");
});
$(".box").draggable({
containment: "body",
cancel: ".btn",
start: function(event, ui) {
setToTop(ui.helper)
}
});
$(".box .btn").click(function() {
$(this).parents(".box").css("display", "none")
});
});
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
font-size: 50px;
font-family: Arial;
background-color: rgb(220, 220, 220);
}
.box {
background-color: yellow;
color: black;
padding: 20px;
display: block;
position: absolute;
border: 2px black;
cursor: all-scroll;
border: 1px solid black;
}
.box:nth-child(1) {
left: 20%;
top: 10%;
}
.box:nth-child(2) {
left: 10%;
top: 15%;
}
.box:nth-child(3) {
left: 25%;
top: 30%;
}
.box:nth-child(4) {
left: 30%;
top: 20%;
}
.box span {
background-color: red;
color: white;
position: absolute;
top: -40px;
right: -40px;
padding: 10px;
cursor: pointer;
border: 1px solid black;
}
<div class="box">Hello <span class="btn">✕</span></div>
<div class="box">Love <span class="btn">✕</span></div>
<div class="box">Freedom <span class="btn">✕</span></div>
<div class="box">Peace <span class="btn">✕</span></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js" integrity="sha256-hlKLmzaRlE8SCJC1Kw8zoUbU8BxA+8kR3gseuKfMjxA=" crossorigin="anonymous"></script>
<script src="https://raw.githubusercontent.com/furf/jquery-ui-touch-punch/master/jquery.ui.touch-punch.min.js"></script>
The cancel method prevents dragging from starting on specified elements.
See More: https://api.jqueryui.com/draggable/#option-cancel
It is not good practice to use the same Variable Names in your code.

Related

How to add inline CSS to dynamically created elements with Javascript?

I would like to add inline CSS to the left and right messages that are generated, for example the left text is red and the right text is blue. (I know it's best to style in the CSS, but I'm testing something else). So I will have this HTML:
<ul class="messages">
<li class="message left appeared">
<div class="text_wrapper">
<p class="text" style="color:red;">blabla</p>
</div>
</li>
<li class="message right appeared">
<div class="text_wrapper">
<p class="text" style="color:blue;">blabla</p>
</div>
</li>
</ul>
Please see the code as reference for the functionality. Many thanks for your help.
(function() {
var Message;
Message = function({
text: text1,
message_side: message_side1
}) {
this.text = text1;
this.message_side = message_side1;
this.draw = () => {
var $message;
$message = $($('.message_template').clone().html());
$message.addClass(this.message_side).find('.text').html(this.text);
$('.messages').append($message);
return setTimeout(function() {
return $message.addClass('appeared');
}, 0);
};
return this;
};
$(function() {
var getMessageText, message_side, sendMessage;
message_side = 'right';
getMessageText = function() {
var $message_input;
$message_input = $('.message_input');
return $message_input.val();
};
sendMessage = function(text) {
var $messages, message;
if (text.trim() === '') {
return;
}
$('.message_input').val('');
$messages = $('.messages');
message_side = message_side === 'left' ? 'right' : 'left';
message = new Message({text, message_side});
message.draw();
return $messages.animate({
scrollTop: $messages.prop('scrollHeight')
}, 300);
};
$('.send_message').click(function(e) {
return sendMessage(getMessageText());
});
$('.message_input').keyup(function(e) {
if (e.which === 13) { // enter key
return sendMessage(getMessageText());
}
});
});
}).call(this);
* {
box-sizing: border-box;
}
.chat_window {
position: absolute;
width: calc(100% - 20px);
max-width: 600px;
height: 440px;
background-color: #fff;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
border: 1px solid #ddd;
overflow: hidden;
}
.messages {
position: relative;
list-style: none;
padding: 20px 10px 0 10px;
margin: 0;
height: 347px;
overflow: scroll;
}
.messages .message {
clear: both;
overflow: hidden;
margin-bottom: 20px;
transition: all 0.5s linear;
opacity: 0;
}
.messages .message.left .text_wrapper {
background-color: #ddd;
margin-left: 20px;
}
.messages .message.left .text_wrapper::after, .messages .message.left .text_wrapper::before {
right: 100%;
border-right-color: #ddd;
}
.messages .message.left .text,
.messages .message.right .text {
color: #000;
margin: 0;
}
.messages .message.right .text_wrapper {
background-color: #ddd;
margin-right: 20px;
float: right;
}
.messages .message.right .text_wrapper::after, .messages .message.right .text_wrapper::before {
left: 100%;
border-left-color: #ddd;
}
.messages .message.appeared {
opacity: 1;
}
.messages .message .text_wrapper {
display: inline-block;
padding: 20px;
width: calc(100% - 85px);
min-width: 100px;
position: relative;
}
.messages .message .text_wrapper::after, .messages .message .text_wrapper:before {
top: 18px;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.messages .message .text_wrapper::after {
border-width: 13px;
margin-top: 0px;
}
.messages .message .text_wrapper::before {
border-width: 15px;
margin-top: -2px;
}
.messages .message .text_wrapper .text {
font-size: 18px;
font-weight: 300;
}
.bottom_wrapper {
position: relative;
width: 100%;
background-color: #fff;
padding: 20px 20px;
position: absolute;
bottom: 0;
}
.bottom_wrapper .message_input_wrapper {
display: inline-block;
height: 50px;
border: 1px solid #bcbdc0;
width: calc(100% - 160px);
position: relative;
padding: 0 20px;
}
.bottom_wrapper .message_input_wrapper .message_input {
border: none;
height: 100%;
box-sizing: border-box;
width: calc(100% - 40px);
position: absolute;
outline-width: 0;
color: gray;
}
.bottom_wrapper .send_message {
width: 140px;
height: 50px;
display: inline-block;
background-color: #ddd;
border: 2px solid #ddd;
color: #000;
cursor: pointer;
transition: all 0.2s linear;
text-align: center;
float: right;
}
.bottom_wrapper .send_message:hover {
color: #000;
background-color: #fff;
}
.bottom_wrapper .send_message .text {
font-size: 18px;
font-weight: 300;
display: inline-block;
line-height: 48px;
}
.message_template {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chat_window">
<ul class="messages"></ul>
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type here..." />
</div>
<div class="send_message">
<div class="icon"></div>
<div class="text">
Send
</div>
</div>
</div>
</div>
<div class="message_template">
<li class="message">
<div class="text_wrapper">
<p class="text"></p>
</div>
</li>
</div>
You can also add:
$(".left").css("color", "yellow");
$(".right").css("color", "blue");
$("li.message.left > div.text_wrapper > p").css('color', 'red');
$("li.message.right > div.text_wrapper > p").css('color', 'blue');
Using jQuery you can add inline style to an element
$(".left").attr("style","whatever");
$(".right").attr("style","whatever");
You can use the classList of every HTML component. Simply, select the DOM element with class left (or right) and use the add method to assign whatever class:
var elementLeft = $('.left')
elementLeft.classList.add('yourClass')
You can also use the methods remove to remove any class, or toggle to toggle some class..
elementLeft.classList.remove('yourClass')
elementLeft.classList.toggle('yourClass')
The Element.classList contains more examples. This solution works without jQuery or others javascript library, but use the standard API.

echo on button class

I'm trying to build a multi step selector which has multiple combinations in every slide. for example hou have btn1, btn2 and btn3. Every button will display other content in the next slide.
It's an inpage multistep slider so I can't use onClick, submit input or something like that.
as you can see in the code below, I'm trying to get an echo on the name or value of the button who has been clicked in the slide before.
var currentSlide = 0,
$slideContainer = $('.slide-container'),
$slide = $('.slide'),
slideCount = $slide.length,
animationTime = 300;
function setSlideDimensions () {
var windowWidth = $(window).width();
$slideContainer.width(windowWidth * slideCount);
$slide.width(windowWidth);
}
function generatePagination () {
var $pagination = $('.pagination');
for(var i = 0; i < slideCount; i ++){
var $indicator = $('<div>').addClass('indicator'),
$progressBarContainer = $('<div>').addClass('progress-bar-container'),
$progressBar = $('<div>').addClass('progress-bar'),
indicatorTagText = $slide.eq(i).attr('data-tag'),
$tag = $('<div>').addClass('tag').text(indicatorTagText);
$indicator.append($tag);
$progressBarContainer.append($progressBar);
$pagination.append($indicator).append($progressBarContainer);
}
$pagination.find('.indicator').eq(0).addClass('active');
}
function goToNextSlide () {
if(currentSlide >= slideCount - 1) return;
var windowWidth = $(window).width();
currentSlide++;
$slideContainer.animate({
left: -(windowWidth * currentSlide)
});
setActiveIndicator();
$('.progress-bar').eq(currentSlide - 1).animate({
width: '100%'
}, animationTime);
}
function goToPreviousSlide () {
if(currentSlide <= 0) return;
var windowWidth = $(window).width();
currentSlide--;
$slideContainer.animate({
left: -(windowWidth * currentSlide)
}, animationTime);
setActiveIndicator();
$('.progress-bar').eq(currentSlide).animate({
width: '0%'
}, animationTime);
}
function postitionSlides () {
var windowWidth = $(window).width();
setSlideDimensions();
$slideContainer.css({
left: -(windowWidth * currentSlide)
}, animationTime);
}
function setActiveIndicator () {
var $indicator = $('.indicator');
$indicator.removeClass('active').removeClass('complete');
$indicator.eq(currentSlide).addClass('active');
for(var i = 0; i < currentSlide; i++){
$indicator.eq(i).addClass('complete');
}
}
setSlideDimensions();
generatePagination();
$(window).resize(postitionSlides);
$('.next').on('click', goToNextSlide);
$('.previous').on('click', goToPreviousSlide);
#charset "UTF-8";
*, html, body {
font-family: "TrebuchetMS", trebuchet, sans-serif;
}
* {
box-sizing: border-box;
}
h1, h2 {
text-align: center;
}
h1 {
font-size: 24px;
line-height: 30px;
font-weight: bold;
}
h2 {
font-size: 18px;
line-height: 25px;
margin-top: 20px;
}
button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: 0;
padding: 14px 50px;
border-radius: 4px;
background-color: #37B595;
color: #FFFFFF;
text-transform: capitalize;
font-size: 18px;
line-height: 22px;
outline: none;
cursor: pointer;
transition: all 0.2s;
}
button:hover {
background-color: #1A7F75;
}
button.previous {
background-color: #A2ACAF;
}
button.previous:hover {
background-color: #5A5F61;
}
.full-width-container {
width: 100%;
min-width: 320px;
}
.sized-container {
max-width: 900px;
width: 100%;
margin: 0 auto;
}
.slide-container {
position: relative;
left: 0;
overflow: hidden;
}
.slide {
float: left;
}
.slide .sized-container {
padding: 75px 25px;
}
.button-container {
border-top: 1px solid black;
overflow: hidden;
padding-top: 30px;
}
.button-container button {
float: right;
margin-left: 30px;
}
.pagination-container {
margin-top: 120px;
}
.pagination {
width: 100%;
text-align: center;
padding: 0 25px;
}
.indicator {
width: 25px;
height: 25px;
border: 4px solid lightgray;
border-radius: 50%;
display: inline-block;
transition: all 0.3s;
position: relative;
}
.indicator .tag {
position: absolute;
top: -30px;
left: 50%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
color: lightgray;
white-space: nowrap;
}
.indicator.active, .indicator.complete {
border-color: #37B595;
}
.indicator.active .tag, .indicator.complete .tag {
color: #37B595;
}
.indicator.complete:after {
content: "✓";
position: absolute;
color: #37B595;
left: 4px;
top: 3px;
font-size: 14px;
}
.progress-bar-container {
width: 10%;
height: 4px;
display: inline-block;
background-color: lightgray;
position: relative;
top: -10px;
}
.progress-bar-container:last-of-type {
display: none;
}
.progress-bar-container .progress-bar {
width: 0;
height: 100%;
background-color: #37B595;
}
<div class="pagination-container full-width-container">
<div class="sized-container">
<div class="pagination"></div>
</div>
</div>
<div class="viewport full-width-container">
<ul class="slide-container">
<li class="slide" data-tag="Basic Info">
<div class="sized-container">
<h1>Slide1.</h1>
<input class="next" name="next" type="button" value="next" />
</div>
</li>
<li class="slide" data-tag="Expertise">
<div class="sized-container">
<h1>Slide2.</h1>
</div>
</li>
</ul>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
Can someone please help me out!

jQuery Slide from left to right distorts CSS

I have a textbox and a button. On clicking the button, if textbox value is blank, then textbox will be highlighted with red borders. On putting focus on the textbox, a validation message will be displayed (slide in from left to right) , something like this:
But after putting the code for sliding in from left to right the validation message is shown as below:
Below is the snippet for the same.
$(document).ready(function(){
$.fn.textWidth = function (text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
$('#btnSave').click(function(){
if (!$('#txtName').val()) {
$('#txtName').addClass('validationInput');
$('#txtName').closest('div').addClass('wrap');
}
else
alert("Success");
});
$('#txtName').on('blur', function () {
if ($(this).val() != "" && $(this).val() != null) {
$(this).removeClass("validationInput");
$(this).closest('div').removeClass("wrap");
}
$(this).parent().parent().siblings().html("");
$(this).parent().parent().siblings().css("display", "none");
});
$('#txtName').on('focus', function () {
if ($(this).hasClass('validationInput')) {
var w = $.fn.textWidth("Please enter name", '12px arial') + 50;
$(this).parent().parent().siblings().html("Please enter name");
//$(this).parent().parent().siblings().css({ "display": "inline-block", "width": w });
$(this).parent().parent().siblings().css({ "width": w }).show('slide', {direction: 'left'}, 1000);
}
});
});
.wrapTextboxDiv {
height: 25px;
}
.col-lg-3 {
width: 25%;
}
.wrap span:first-child {
display: flex;
overflow: hidden;
position: relative;
width: 100%;
}
.wrap span:first-child .input-holder::after {
border-color: red;
border-style: solid;
border-width: 5px;
box-shadow: 0 0 0 1px #ffffe0;
content: "";
height: 0;
position: absolute;
right: -5px;
top: -5px;
transform: rotate(45deg);
width: 0;
}
input.vtooltips[type="text"] {
display: inline;
height: 20px;
position: relative;
}
.vspan {
background: #dc000c none repeat scroll 0 0;
border: 1px solid #6d6d6d;
border-radius: 4px;
box-shadow: 2px 2px 0 #afb1b1;
color: #fff;
display: none;
font-family: Arial;
font-size: 12px;
height: 20px;
line-height: 15px;
margin-left: 101%;
opacity: 1;
padding-left: 5px;
padding-right: 5px;
position: relative;
text-align: center;
top: -23px;
z-index: 1000;
}
.validationInput, .validationInput:focus, .validationInput:hover {
background-color: #ffffe0 !important;
border: 1px solid red !important;
height: 20px;
}
.mandatoryText {
background-color: #fafad2 !important;
}
.textbox {
border: 1.5px solid #f2ca8c;
border-radius: 4px !important;
height: 23px !important;
width:90%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div class="col-lg-3 wrapTextboxDiv">
<span>
<span class="input-holder">
<input type="text" class="mandatoryText vtooltips form-control textbox" style="width: 100%; vertical-align: top; border-radius: 4px;" maxlength="100" id="txtName" name="tname">
</span>
</span>
<span class="vspan"></span>
</div>
<br/>
<br/>
<input type="button" id="btnSave" value="Save"/>
What am I doing wrong? Any help will be appreciated.
Remove margin-left and add left:100% in .vspan class.
$(document).ready(function(){
$.fn.textWidth = function (text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
$('#btnSave').click(function(){
if (!$('#txtName').val()) {
$('#txtName').addClass('validationInput');
$('#txtName').closest('div').addClass('wrap');
}
else
alert("Success");
});
$('#txtName').on('blur', function () {
if ($(this).val() != "" && $(this).val() != null) {
$(this).removeClass("validationInput");
$(this).closest('div').removeClass("wrap");
}
$(this).parent().parent().siblings().html("");
$(this).parent().parent().siblings().css("display", "none");
});
$('#txtName').on('focus', function () {
if ($(this).hasClass('validationInput')) {
var w = $.fn.textWidth("Please enter name", '12px arial') + 50;
$(this).parent().parent().siblings().html("Please enter name");
//$(this).parent().parent().siblings().css({ "display": "inline-block", "width": w });
$(this).parent().parent().siblings().css({ "width": w }).show('slide', {direction: 'left'}, 1000);
}
});
});
.wrapTextboxDiv {
height: 25px;
}
.col-lg-3 {
width: 25%;
}
.wrap span:first-child {
display: flex;
overflow: hidden;
position: relative;
width: 100%;
}
.wrap span:first-child .input-holder::after {
border-color: red;
border-style: solid;
border-width: 5px;
box-shadow: 0 0 0 1px #ffffe0;
content: "";
height: 0;
position: absolute;
right: -5px;
top: -5px;
transform: rotate(45deg);
width: 0;
}
input.vtooltips[type="text"] {
display: inline;
height: 20px;
position: relative;
}
.vspan {
background: #dc000c none repeat scroll 0 0;
border: 1px solid #6d6d6d;
border-radius: 4px;
box-shadow: 2px 2px 0 #afb1b1;
color: #fff;
display: none;
font-family: Arial;
font-size: 12px;
height: 20px;
line-height: 15px;
/* margin-left: 101%;*/ /* Remove this*/
opacity: 1;
padding-left: 5px;
padding-right: 5px;
position: relative;
text-align: center;
top: -23px;
z-index: 1000;
left:100%;
}
.validationInput, .validationInput:focus, .validationInput:hover {
background-color: #ffffe0 !important;
border: 1px solid red !important;
height: 20px;
}
.mandatoryText {
background-color: #fafad2 !important;
}
.textbox {
border: 1.5px solid #f2ca8c;
border-radius: 4px !important;
height: 23px !important;
width:90%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div class="col-lg-3 wrapTextboxDiv">
<span>
<span class="input-holder">
<input type="text" class="mandatoryText vtooltips form-control textbox" style="width: 100%; vertical-align: top; border-radius: 4px;" maxlength="100" id="txtName" name="tname">
</span>
</span>
<span class="vspan"></span>
</div>
<br/>
<br/>
<input type="button" id="btnSave" value="Save"/>
Simply do this with float:left property , add float to this class .vspan , just try with this snippet
$(document).ready(function(){
$.fn.textWidth = function (text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
$('#btnSave').click(function(){
if (!$('#txtName').val()) {
$('#txtName').addClass('validationInput');
$('#txtName').closest('div').addClass('wrap');
}
else
alert("Success");
});
$('#txtName').on('blur', function () {
if ($(this).val() != "" && $(this).val() != null) {
$(this).removeClass("validationInput");
$(this).closest('div').removeClass("wrap");
}
$(this).parent().parent().siblings().html("");
$(this).parent().parent().siblings().css("display", "none");
});
$('#txtName').on('focus', function () {
if ($(this).hasClass('validationInput')) {
var w = $.fn.textWidth("Please enter name", '12px arial') + 50;
$(this).parent().parent().siblings().html("Please enter name");
//$(this).parent().parent().siblings().css({ "display": "inline-block", "width": w });
$(this).parent().parent().siblings().css({ "width": w }).show('slide', {direction: 'left'}, 1000);
}
});
});
.wrapTextboxDiv {
height: 25px;
}
.col-lg-3 {
width: 25%;
}
.wrap span:first-child {
display: flex;
overflow: hidden;
position: relative;
width: 100%;
}
.wrap span:first-child .input-holder::after {
border-color: red;
border-style: solid;
border-width: 5px;
box-shadow: 0 0 0 1px #ffffe0;
content: "";
height: 0;
position: absolute;
right: -5px;
top: -5px;
transform: rotate(45deg);
width: 0;
}
input.vtooltips[type="text"] {
display: inline;
height: 20px;
position: relative;
}
.vspan {
background: #dc000c none repeat scroll 0 0;
border: 1px solid #6d6d6d;
border-radius: 4px;
box-shadow: 2px 2px 0 #afb1b1;
color: #fff;
display: none;
font-family: Arial;
font-size: 12px;
height: 20px;
line-height: 15px;
left: 100%;
opacity: 1;
padding-left: 5px;
padding-right: 5px;
position: relative;
text-align: center;
top: -23px;
z-index: 1000;
float:left;
}
.validationInput, .validationInput:focus, .validationInput:hover {
background-color: #ffffe0 !important;
border: 1px solid red !important;
height: 20px;
}
.mandatoryText {
background-color: #fafad2 !important;
}
.textbox {
border: 1.5px solid #f2ca8c;
border-radius: 4px !important;
height: 23px !important;
width:90%;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
</head>
<body>
<div class="col-lg-3 wrapTextboxDiv">
<span>
<span class="input-holder">
<input type="text" class="mandatoryText vtooltips form-control textbox" style="width: 100%; vertical-align: top; border-radius: 4px;" maxlength="100" id="txtName" name="tname">
</span>
</span>
<span class="vspan"></span>
</div>
<br/>
<br/>
<input type="button" id="btnSave" value="Save"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</body>
</html>

Trying to get my Game Loop right

I am trying to do my very first simple game.
My question is: why is my game loop not working? If you see the code, I tried to put all the game code inside an if. The idea is: "if game over is false, execute the game, else (when my humanHungerBar reaches 0) the game is over".
Can you help me here? Thanks a lot
<!doctype html>
<html>
<head>
<style>
body {
-webkit-user-select: none;
}
#screen {
position: relative;
left: 480px;
top: 30px;
border: 2px solid black;
height: 500px;
width: 400px;
display: block;
}
#myCash {
position: relative;
width: 90px;
height: 40px;
top: 7px;
left: 5px;
border: 5px solid lightgreen;
text-align: center;
vertical-align: middle;
line-height: 40px;
color: green;
font-weight: bolder;
font-size: 20px;
}
#humanHunger {
position: relative;
width: 90px;
height: 90px;
top: 20px;
left: 280px;
border: 1px solid black;
}
#humanHungerContainer {
position: relative;
width: 100%;
height: 20px;
top: 20px;
border: 1px solid black;
background-color: red;
}
#humanHungerBar {
position: absolute;
width: 76%;
height: 18px;
border: 1px solid green;
background-color: green;
}
#moneyMaker {
position: relative;
width: 300px;
height: 450px;
top: -850px;
left: 100px;
border: 3px solid green;
background-image: url("moneyMakerBackground.png");
}
#jobInstructions {
position: absolute;
width: 250px;
height: 50px;
border: 3px solid orange;
top: 20px;
left: 22px;
background-color: lightgreen;
text-align: center;
}
#workingHours {
position: absolute;
width: 250px;
height: 50px;
border: 3px solid orange;
top: 90px;
left: 22px;
background-color: lightgreen;
text-align: center;
vertical-align: middle;
line-height: 50px;
}
#workCounter {
position: absolute;
width: 60px;
height: 50px;
border: 3px solid orange;
top: 250px;
left: 22px;
background-color: lightgreen;
text-align: center;
}
#clickingArea {
position: absolute;
width: 250px;
height: 50px;
border: 3px solid orange;
top: 170px;
left: 22px;
background-color: lightgreen;
filter: saturate(100%);
}
#clickingArea:hover {
filter: saturate(190%);
}
#dollar {
position: relative;
left: 80px;
top: 5px;
}
#nakedHuman {
position: absolute;
top: 25px;
left: 120px;
}
#clothesScreen {
position:relative;
top: -400px;
left: 900px;
border: 2px solid black;
width: 300px;
height: 400px;
overflow: auto;
}
#lumberShirt {
position: absolute;
top: 165px;
left: 120px;
display:none;
}
#coffeeStainedTShirt {
position: absolute;
top: 165px;
left: 120px;
display:none;
}
#regularJeans {
position: absolute;
top: 328px;
left: 145px;
display:none;
}
#lumberShirtMiniContainer {
position: relative;
top: 10px;
left: 10px;
}
#coffeeStainedTShirtMiniContainer {
position: relative;
top: 30px;
left: 10px;
}
#regularJeansMiniContainer {
position: relative;
top: 60px;
left: 20px;
}
#burgerMiniContainer {
position: relative;
top: 90px;
left: 10px;
}
#lumberShirtPrice {
position: absolute;
top: 20px;
left: 100px;
border: 3px solid orange;
width: 50px;
height: 20px;
text-align: center;
vertical-align: middle;
line-height: 20px;
background-color: orange;
}
#buyButtonLumber {
position: absolute;
top: 60px;
left: 100px;
border: 3px solid lightgreen;
width: 30px;
height: 15px;
}
#buyButtonCoffee {
position: absolute;
top: 60px;
left: 100px;
border: 3px solid lightgreen;
width: 30px;
height: 15px;
}
#buyButtonRegularJeans {
position: absolute;
top: 60px;
left: 100px;
border: 3px solid lightgreen;
width: 30px;
height: 15px;
}
#buyButtonBurger {
position: absolute;
top: 60px;
left: 100px;
border: 3px solid lightgreen;
width: 30px;
height: 15px;
}
</style>
</head>
<body>
<div id="screen">
<img id="nakedHuman" src="nakedHuman2.png" width="139.46" height="450">
<img id="lumberShirt" src="lumberShirt.png" width="139.46" height="158.51">
<img id="coffeeStainedTShirt" src="coffeeStainedTShirt.png" width="139.46" height="158.51">
<img id="regularJeans" src="regularJeans.png" width="89" height="152.72">
<div id="myCash"></div>
<div id="humanHunger">
<div id="humanHungerContainer">
<div id="humanHungerBar"></div>
</div>
</div>
</div>
<div id="clothesScreen">
<div id="lumberShirtMiniContainer">
<img id="lumberShirtMini" src="lumberShirt.png" width="70.38" height="80">
<div id="lumberShirtPrice"></div>
<div id="buyButtonLumber">Buy</div>
</div>
<div id="coffeeStainedTShirtMiniContainer">
<img id="coffeeStainedTShirtMini" src="coffeeStainedTShirt.png" width="70.38" height="80">
<div id="buyButtonCoffee">Buy</div>
</div>
<div id="regularJeansMiniContainer">
<img id="regularJeansMini" src="regularJeans.png" width="46.62" height="80">
<div id="buyButtonRegularJeans">Buy</div>
</div>
<div id="burgerMiniContainer">
<img id="burger" src="burger.png" width="94.11" height="80">
<div id="buyButtonBurger">Buy</div>
</div>
</div>
<div id="moneyMaker">
<div id="jobInstructions">You work on a click factory, so get to clickin'!!</div>
<div id="workingHours"></div>
<div id="clickingArea"><img src="dollar.png" id="dollar" width="82.55" height="42"></div>
<div id="workCounter"></div>
</div>
<script>
window.onload = function () {
var gameOver = false;
if (!gameOver) {
var lumberShirtPrice = document.getElementById("lumberShirtPrice");
lumberShirtPrice.innerHTML = 7;
var myCash = document.getElementById("myCash");
myCash.innerHTML = 45;
var buyButtonLumber = document.getElementById("buyButtonLumber");
buyButtonLumber.addEventListener("click", substractItemPriceFromMyCash);
var negateFX = new Audio('negate1.wav');
function substractItemPriceFromMyCash() {
var a = parseInt(lumberShirtPrice.innerHTML);
var b = parseInt(myCash.innerHTML);
if (a > b) {
negateFX.play();
}
else {
myCash.innerHTML -= lumberShirtPrice.innerHTML;
console.log("you bought the lumber shirt");
}
}
var workingHoursScreen = document.getElementById("workingHours");
workingHoursScreen.innerHTML = 0;
var workCounter = document.getElementById("workCounter");
workCounter.innerHTML = 0;
var allowedToWork = false;
var workingHoursChronometer = setInterval(incrementWorkingHoursChronometer, 1000);
function incrementWorkingHoursChronometer () {
var a = parseInt(workingHoursScreen.innerHTML);
if(a < 10) {
workingHoursScreen.innerHTML++;
}
else if (a == 10) {
workingHoursScreen.innerHTML = 0;
workCounter.innerHTML++;
}
var b = parseInt(workCounter.innerHTML);
if (b == 4) {
workCounter.innerHTML = 0;
}
if (b % 2 == 0) {
allowedToWork = true;
}
else if (b % 2 == 1) {
allowedToWork = false;
}
}
var coinFX = new Audio('coin1.wav');
var clickingAreaBox = document.getElementById("clickingArea");
clickingAreaBox.addEventListener("click", giveMeMoney);
function giveMeMoney() {
if(allowedToWork) {
myCash.innerHTML++;
coinFX.play();
}
else {
negateFX.play();
}
}
var humanHungerBar = document.getElementById("humanHungerBar");
var barWidth = 76;
humanHungerBar.style.width = barWidth + '%';
var humanHungerBarDecrement = setInterval (decreaseHumanHungerBar, 700);
function decreaseHumanHungerBar () {
if (barWidth > 0) {
humanHungerBar.style.width = barWidth + '%';
barWidth--;
}
}
var buyButtonBurger = document.getElementById("buyButtonBurger");
var burgerPrice = 15;
buyButtonBurger.addEventListener("click", buyBurgerRestoreLifeAndDecreaseMoney);
function buyBurgerRestoreLifeAndDecreaseMoney() {
var a = parseInt(myCash.innerHTML);
if (a >= burgerPrice){
if(barWidth < 92) {
barWidth += 10;
myCash.innerHTML -=burgerPrice;
}
else if (barWidth == 1) {
gameOver = true;
console.log("bar is 1");
}
else {
negateFX.play();
}
}
else {
negateFX.play();
}
}
}
else {
document.getElementById("screen").style.display = 'none';
}
}
</script>
</body>
</html>
So you have written a script that executes one time. It goes from beginning to end, and then stops. So what you want to do is write a script that repeats over and over until the game ends. So here's a super brief example of how you might do that in javascript:
while (!gameOver) {
// do game code
}
BUT WAIT!!!
So the code inside that while loop will keep on happening over and over until the gameOver variable is true. But if you try to use that code, your game will probably freeze! Why? Because the browser is executing the code inside the while loop as fast as it possibly can. But if you'd like your game to run at a certain frame-per-second rate, you probably want to use a javascript timeout. So try something like this:
setInterval(function() {
// do game code
}, 1000/60);
That is the absolutely bare minimum that you'll need for a technical "game loop". However, this is not really the recommended approach for starting to create a browser-based game. Try doing some research and checking out things like this and this.

Why is my javascript not functioning?

I'm using a layout from Codepen: http://codepen.io/trhino/pen/ytoqv
and I have put certain parts of that code into my html but it is not functioning. Can anybody tell me why and what I can do to fix it? All I want from the codepen tutorial is the actual image gallery effect and the 'click to expand' and 'collapse' buttons.
Here is what my site looks like at the minute (ignore the stretched photos, I will be correcting this once I have sorted the javascript)
http://me14ch.leedsnewmedia.net/portfolio/photo.html
Really appreciate ANY help! This is my code:
<h2>(click on the box to expand gallery)</h2>
<div class="wrap">
<div id="picture1" class="deck">
<img src="http://www.me14ch.leedsnewmedia.net/portfolio/gallery/newyork1.JPG">
</a>
</div>
<div id="picture2" class="deck">
<img src="http://www.me14ch.leedsnewmedia.net/portfolio/gallery/newyork2.JPG">
</a></div>
<div id="picture3" class="deck">
<img src="http://www.me14ch.leedsnewmedia.net/portfolio/gallery/newyork3.JPG">
</a></div>
<div id="picture4" class="deck">
<img src="http://www.me14ch.leedsnewmedia.net/portfolio/gallery/newyork4.JPG">
</a></div>
<div id="picture5" class="deck">
<img src="http://www.me14ch.leedsnewmedia.net/portfolio/gallery/newyork5.JPG">
</a></div>
</div>
<div id="close"><p>« collapse gallery</p></div>
<div id="lightbox">
<div id="lightwrap">
<div id="x"></div>
</div>
This is the CSS
/* gallery */
*, *::before, *::after {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
p {
font-family: arial, helvetica, sans-serif;
font-size: 24px;
color: #6CBDEB;
text-shadow: 1px 1px 1px #000;
}
.wrap {
position: relative;
width: 1125px;
height: 200px;
margin: 0 auto;
}
.deck {
margin: 20px;
border: 3px solid #FADBC8;
height: 202px;
width: 202px;
position: absolute;
top: 0;
left: 0;
transition: .3s;
cursor: pointer;
font-size: 50px;
line-height:200px;
text-align: center;
}
.deck a {
color: black;
}
.deck img {
height: 200px;
width: 200px;
}
.album {
border: 1px solid #FADBC8;
height: 200px;
width: 200px;
float: left;
transition: .3s;
position: relative;
}
#close {
position: relative;
display: none;
width: 1125px;
margin: 30px auto 0;
}
#close p {
cursor: pointer;
text-align: right;
margin: 0 20px 0;
}
#lightbox {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.7);
display: none;
z-index: 999;
}
#lightwrap {
position: relative;
margin: 0 auto;
border: 5px solid black;
top: 15%;
display: table;
}
#lightwrap img {
display: table-cell;
max-width: 600px;
}
#x {
position: absolute;
top: 2px;
right: 2px;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAbCAMAAAC6CgRnAAAAPFBMVEX///8AAAD9/f2CgoKAgIAAAAAAAAAAAABLS0sAAAAAAACqqqqqqqq6urpKSkpISEgAAAC7u7u5ubn////zbsMcAAAAE3RSTlMASv6rqwAWS5YMC7/AyZWVFcrJCYaKfAAAAHhJREFUeF590kkOgCAQRFEaFVGc+/53FYmbz6JqBbyQMFSYuoQuV+iTflnstI7ssLXRvMWRaEMs84e2uVckuZe6knL0hiSPObXhj6ChzoEkIolIIpKIO4joICAIeDd7QGIfCCjOKe9HEk8mnxpIAup/F31RPZP9fAG3IAyBSJe0igAAAABJRU5ErkJggg==);
width: 27px;
height: 27px;
cursor: pointer;
}
and this is the Javascript:
var i, expand = false;
function reset() {
$('.deck').css({
'transform': 'rotate(0deg)',
'top' : '0px'
});
}
//expands and contracts deck on click
$('.deck').click(function (a) {
if (expand) {
a.preventDefault();
var imgSource = $(this).children().attr('href');
$('#lightwrap').append('<img src="' + imgSource + '" id="lb-pic">');
$('#lightbox, #lightwrap').fadeIn('slow');
} else {
var boxWidth = $('.deck').width();
$('.deck').each(function (e) {
$(this).css({
'left': boxWidth * e * 1.1 + 'px'
});
expand = true;
$('#close').show();
});
}
});
//close lightbox
$('#x, #lightbox').click(function(){
$('#lightbox').fadeOut('slow');
$('#lightwrap').hide();
$('#lb-pic').remove();
});
//prevent event bubbling on lightbox child
$('#lightwrap').click(function(b) {
b.stopPropagation();
});
$('#close').click(function(){
$(this).hide();
$('.deck').css({'left': '0px'});
expand = false;
});
$('.deck:last-child').hover(
//random image rotation
function() {
if (expand === false) {
$('.deck').each(function () {
i++;
if (i < $('.deck').length) {
var min = -30,
max = 30,
random = ~~(Math.random() * (max - min + 1)) + min;
$(this).css({
'transform' : 'rotate(' + random + 'deg)',
'top' : random + 15 + 'px'
});
}
});
}
//straightens out deck images when clicked
$('.deck').click(
function (a) {
a.preventDefault();
reset();
});
},
//undo image rotation when not hovered
function () {
i = 0;
reset();
}
);
Just enclose your javascript in a $( document ).ready() function in order to execute on load of the page:
$( document ).ready(function() {
//paste javascript code here
});
The Result will be this:
Here is also a jsBin for it

Categories

Resources