Problem when executing a script with onblur - javascript

I take the liberty of posting this topic because I find myself in a situation that I can't explain.
I created a stopwatch that allows to record the time spent when clicking on stop (it also sends the client id, the comment left by the employee, the creation date and the person who did the work).
For security reasons, I blocked the submit button once the user has clicked once. I also offer the possibility to save a task and resume it later. And here, while the html code of the stopwatch is identical, it doesn't work anymore. Indeed, you can click twice before it freezes (and not once as before).
Here is what the button looks like when you click :
Here is the corresponding JavaSript code :
function verifComm(text){
console.log('verifComm');
if(text.value.length < 5){
return false;
}
else {
var n = 1;
btnSend = document.getElementById("envoi");
btnSave = document.getElementById("sauv");
btnSend.addEventListener('click', function desactiverEnvoiBouton(){
document.getElementById('envoi').value='Envoi en cours...';
document.getElementById('envoi').style.opacity = "0.5";
if(n>1){
document.getElementById('envoi').disabled=true;
}
n = n+1;
console.log('Clic sur envoi');
});
btnSave.addEventListener('click', function desactiverSauvegardeBouton(){
document.getElementById('sauv').value='Sauvegarde en cours...';
document.getElementById('sauv').style.opacity = "0.5";
if(n>1){
document.getElementById('sauv').disabled=true;
}
n = n+1;
});
return true;
}
}
// Vérification avant envoi du formulaire
function verifForm(f){
var CommOk = verifComm(f.commentaireEnregistre);
var CommSaveOk = verifComm(f.commentaireSauvegarde);
if( (CommOk) || (CommSaveOk)){
return true;
}
else{
alert("Veuillez commenter la tâche (minimum 5 caractères)");
return false;
}
}
And this is what the code of the page looks like: (I made a screenshot because I can't share my code, he doesn't want to publish the topic otherwise)
If you need more code or explanations, don't hesitate to let me know.
Thank you in advance for your answers.
I look forward to hearing from you,
Damien

Related

Firebase Hosted JS Game Skipping Lines of Code

I made a little game with HTML/JS/CSS to learn more javascript that I have hosted as a firebase web app right now. I was playing it after deploying and watching the console in Google chrome and realized that my game is passing over big important sections of code. I can link to the game if anyone wants to see these "skips" in action. My two big problems are that the tile sometimes returns true for an enemy but does not trigger a fight and sometimes the game does not check if the player should be alive. This doesn't happen every time, just some of the time. I can also share anything else from the project that would be helpful. This is really the first time I've used JS outside of simple tags for a webpage so try not to judge it too harshly. Thanks in advance!
The pieces in question that are being skipped are:
//decide if a tile has an enemy
function hasEnemy(){
let roll = Math.random();
console.log(roll);
if(roll > .6666){
return true;
}else{
return false;
}
}
//there is one gameView.onXClick for each cardinal direction.
//button functions
gameView.onNorthClick = function(){
console.log("north");
oPos = thePlayer.pos;
if ((thePlayer.pos - 5) < 0){
null;
}else{
thePlayer.pos -= 5;
gameView.updateLoc(oPos, thePlayer.pos);
if(thePlayer.pos == 12){
gameView.updateNar("You are home");
gameView.homeMenu();
}else{
gameView.updateNar("You travel North");
console.log(hasEnemy());
if(hasEnemy()){
fightEnemy();
}else{
this.updateNar("Nothing around...");
}
}
}
}
and a very important piece of the game:
//player hits
gameView.onHitClick = function(){
console.log("You Hit");
thePlayer.hp = thePlayer.hp - curEnemy.atk;
curEnemy.hp = curEnemy.hp - thePlayer.atk;
gameView.updateFight(thePlayer.hp, thePlayer.atk, thePlayer.def, curEnemy.hp, curEnemy.atk, curEnemy.def);
this.updateNar("You hit for " + thePlayer.atk);
if(enemyLive(curEnemy.hp) == false){
this.updateNar("You beat the enemy");
thePlayer.kc += 1;
thePlayer.exp += curEnemy.expw;
thePlayer.gold += curEnemy.gold;
gameView.mapScene();
gameView.moveMenu();
gameView.updateLoc(oPos, thePlayer.pos);
}else if(playerLive(thePlayer.hp) == false) {
gameView.loseScene(thePlayer.kc, thePlayer.gold);
gameView.loseMenu();
}
}
//check if the player is alive
function playerLive(php){
if(php <= 0){
return false;
}else{
return true;
}
}

Display only certain amount of wordpress comments

Im trying to figure out how to in wordpress display only first two comments and hide rest and add button that reveal all these hidden messages if needed. Pagination give me only two msg per page and thats not im looking for. Can someone give me an idea how I can this achieve or point me to articles about this?
Thanks
here is a plugin that should do the job: https://wordpress.org/plugins/comment-load-more/
It is a bit outdated (3 years ago) so you should check if the code is still valid and compatible.
In " Settings > Comment Load" you should be able to set the number of desired comments to show first.
Indeed, in this guide - http://www.wpbeginner.com/plugins/how-to-easily-lazy-load-comments-in-wordpress/ - you will find how to lazy load all comments. Probably, with some modification, you can adapt it to your need as well.
Cheers!
// This function hide comments if is there more than two and add show more button
function fds_comments () {
var commentWrap = document.getElementById('comment-list');
var commentChilderns = commentWrap.children;
for (var i = 2; i < commentChilderns.length; i++) {
commentChilderns[i].style.display = "none";
}
commentWrap.innerHTML = commentWrap.innerHTML + "<button id='more-comments' onclick='fds_all_comments()'type='button' >Show all comments</button>";
}
//This function reveal all comments (used on SHOW MORE btn)
function fds_all_comments(){
var commentWrap = document.getElementById('comment-list');
var commentChilderns = commentWrap.children;
for (var i = 0; i < commentChilderns.length; i++) {
commentChilderns[i].style.display = "block";
}
}
// problem: comments hidden after submit
// solved: This additional code reveal comments after SUBMIT
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
fds_all_comments();
}
}
// function used on SUBMIT button
function fds_all_on_submit(){
sessionStorage.setItem("reloading", "true");
document.location.reload();
}

if/else statement confusion

I'm thinking about making a small semi-game where you respond to a mysterious void about things. The user sees a question on-screen, types a response in the textbox and clicks the reply button, and the script replies.
My main problem is to understand the logic behind all this.
For example:
Do you like apples?
A1:Yes
A2:No
if(yes){
say this
} else if(no){
say that
}
What would be the appropriate syntax in this case? Because i'm really really confused right now, it may seem like a very noob-question, but jQuery is getting on my nerves.
var input = document.querySelector('input'),
output = document.getElementById('output');
input.onkeyup = function(event) {
switch (this.value.toLowerCase()) {
case 'chicken':
output.innerText = "I like chicken too";
break;
case 'meat':
output.innerText = "mmmmm, meat!!";
break;
default:
break;
}
};
<form>
<input type="text" />
<div id="output">Huh?</div>
</form>
You could also just do this
var isYes = true;
(isYes) ? /* Do this */ : /* Do this */ ;
Saves you lines of code
Edit: As you had requested I have created a snippet. Try it out, type in chicken/meat
Since you are using a Boolean (true,false) type of scenario you can can just use an if/else type of statement:
var is_yes = true;
if(is_yes){
// Do this
} else {
// Do that
}

Javascript style type

I would like to implement it in a way where when the user has visited my page for the first time.
They will have a pop up appearing like a forum message " Hi , you've just visited our forum "
So when the second time the same user visit , the pop up will disappear .
Here's my code I'm working on :
var beenherecookie = 'FE44been644';
var beenherebegin = document.cookie.indexOf(beenherecookie);
if (beenherebegin > -1){
//Want to implement the code of when user enter first time , "style="display:none;"
else{
function setTimeout("style="display:block;", 60000 * 10); ; //set to 1000 X number of desired delay seconds. So 2 minutes (120 seconds) is 120 X 1000 =
120000
WriteCookie("FE44been644","yes");}
Here's my HTML code for the style::
style="javascript:meh(the function of the style which changes)"
So here's the situation :
When the user visit the website for the first time,
The javascript function meh would be style="display:none"
If the user has entered the website previously
The javascript function meh would be style="display:block"
I need some favors thanks in advance
There are several ways you can implement the scenario..
declare your meh function
var meh = function(){}
if (beenherebegin > -1){
meh = function(){
document.getElementById('popupID').style.display='none';
}
}
else{
meh = function(){
document.getElementById('popupID').style.display='block';
}
}
EDIT
var isFirstTime = false;
var popupHandler = function(firstTime){
if(firstTime){
return "block";
}
else{
return "none";
}
}
if (beenherebegin > -1){
isFirstTime = false;
}
else{
isFirstTime = true;
}
document.getElementById('popupID').style.display= popupHandler(isFirstTime);
Hello,
Once you use the cookie profiling to identify if the user has visited before. You can use document.getElementById.show() and document.getElementById.hide() methods to achieve what you are trying to do. There would be a div element enclosing the popup code, so you can use that. Please tell me if this helps or not. Additionally you can also use jquery methods for show/hide.
Thank You

Disappearing Menu Commands After User Input in Tampermonkey

Tampermonkey is an extension for Google Chrome that attempts to emulate the functionality of Greasemonkey. To be clear, I got my script to work in Chrome and the default JavaScript changes to show up. I wanted to test the menu commands, however, and entered a 6-digit hex color code after clicking on the command in the Tampermonkey menu. I reloaded the page, and the commands disappeared from the menu! My script was still there (and the checkbox was ticked).
No matter what I did or what code I changed, I could never emulate this initial functionality after that user-defined input was set. This leads me to believe that there's some persistent data that I can't delete that's causing my script to fail prematurely. NOTE: This exact script works perfectly and without errors in Firefox.
This is obviously not a Tampermonkey forum, but people here seem very knowledgeable about cross-platform compatility. I didn't hear a single peep from the Chrome console after all of the changes below, and I'm really just out of ideas at this point. Here are some things I've tried (with no success). Any console errors are listed:
Changing jQuery version from 1.5.1 to 1.3.2
Calling localStorage.getItem('prevoColor') from console after page load (both values null)
Changing client-side storage from localStorage to get/setValue
Calling GM_getValue from the console = ReferenceError: GM_getValue is not defined
Deleting localStorage entries for veekun.com in Chrome options
Refreshing, Re-installing the script, and restarting the browser more times than I can count
Repeating all of the above commands using Firebug Lite (bookmarklet)
Here's the code I was using:
// ==UserScript==
// #name Veekun Comparison Highlighter
// #namespace tag://veekun
// #description Highlights moves exclusive to pre-evolutions on veekun.com's family comparison pages (user-defined colors available)
// #include http://veekun.com/dex/gadgets/*
// #author Matthew Ammann
// #version 1.0.3
// #date 3/11/11
// #require http://sizzlemctwizzle.com/updater.php?id=98824
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
/*
Goal: Change checkmark color & move name to user-specified color on family comparison pages if
[DONE] Baby poke has a LEVEL-UP move unlearned by any evolutions
[DONE] a) Make sure move is not a TM or tutor move
[DONE] Any other mid-evolution has a move unlearnable by a final evo (Caterpie, Weedle families)
[DONE] a) Make sure move is not a TM or tutor move
[DONE] Any pre-evo has a TUTOR move unlearned by any evo (Murkrow in HG/SS)
[] Implement auto-update after uploading to userscripts.org
Credits: Brock Adams, for helping with Chrome compatibility
Metalkid, for the jQuery consult
*/
var isLevelupMove = false;
var isTutorMove = false;
var isTM = false;
var TMhead = $('#moves\\:machine');
var hasSecondEvo = false;
var hasFinalEvo1 = false;
var hasFinalEvo2 = false;
var header = $('.header-row').eq(1);
var TMmoves = new Array();
//This section deals with the user-defined colors
GM_registerMenuCommand("Color for pre-evolutionary-only moves", prevoColorPrompt)
GM_registerMenuCommand("Color for first evolution-only moves", evoColorPrompt)
var prevoColor = GM_getValue('prevoColor', '#FF0000');
var evoColor = GM_getValue('evoColor', '#339900');
function prevoColorPrompt()
{
var input = prompt("Please enter a desired 6-digit hex color-code for pre-evolutionary pokemon:")
GM_setValue('prevoColor', '#'+input);
}
function evoColorPrompt()
{
var input = prompt("Please enter the desired 6-digit hex color-code for first-evolution pokemon:")
GM_setValue('evoColor', '#'+input);
}
//This loop tests each 'th' element in a sample header row, determining how many Evos are currently present in the chart.
$('.header-row').eq(1).find('th').each(function(index)
{
if($(this).find('a').length != 0)
{
switch(index)
{
case 2:
hasSecondEvo = true;
break;
case 3:
hasFinalEvo1 = true;
break;
case 4:
hasFinalEvo2 = true;
break;
}
}
});
//All 'tr' siblings are TM moves, since it's the last section on the page
//This array puts only the names of the available TMs into the TMmoves array
TMhead.nextAll().each(function(index)
{
TMmoves.push($(this).children(":first").find('a').eq(0).html());
});
$('tr').each(function(index)
{
var moveName = $(this).children(":first").find('a').eq(0).html();
moveName = $.trim(moveName);
switch($(this).attr('id'))
{
case 'moves:level-up':
isLevelupMove = true;
break;
case 'moves:egg':
isLevelupMove = false;
break;
case 'moves:tutor':
isTutorMove = true;
case 'moves:machine':
isTM = true;
}
if(isLevelupMove || isTutorMove)
{
var babyMoveCell = $(this).find('td').eq(0);
babyMoveText = $.trim(babyMoveCell.html());
secondEvoCell = babyMoveCell.next();
secondEvoText = $.trim(secondEvoCell.html());
finalEvo1Cell = secondEvoCell.next();
finalEvo1Text = $.trim(finalEvo1Cell.html());
finalEvo2Cell = finalEvo1Cell.next();
finalEvo2Text = $.trim(finalEvo2Cell.html());
//This checks if evolutions have checkmarks
if(babyMoveText.length > 0)
{
if(hasSecondEvo && secondEvoText.length == 0 || hasFinalEvo1 && finalEvo1Text.length == 0 ||
hasFinalEvo2 && finalEvo2Text.length == 0)
{
//See if the move is a TM before proceeding
var tm = tmCheck(moveName);
if(!tm)
{
if(secondEvoText.length > 0)
{
babyMoveCell.css("color", evoColor);
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor); //highlights move name
}
else
{
babyMoveCell.css("color", prevoColor);
babyMoveCell.prev().find('a').eq(0).css("color", prevoColor);
}
}
}
}
else if(secondEvoText.length > 0)
{
if(hasFinalEvo1 && finalEvo1Text.length == 0 || hasFinalEvo2 && finalEvo2Text.length == 0)
{
var tm = tmCheck(moveName);
if(!tm)
{
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor);
}
}
}
}
});
function tmCheck(input)
{
var isTM = false;
//Iterate through TMmoves array to see if the input matches any entries
for(var i = 0; i < TMmoves.length; i++)
{
if(input == TMmoves[i])
{
isTM = true;
break;
}
}
if(isTM == true)
return true;
else
return false;
}
//alert("evoColor: " + localStorage.getItem('evoColor') + ". prevoColor: " + localStorage.getItem('prevoColor'));
Any ideas as to why this is happening?
EDIT: I messaged sizzlemctwizzle about this problem, and this was his reply: "Tampermonkey’s #require implementation is incorrect. It downloads my updater far too often so I have banned it from using my updater via browser sniffing. My server just can’t handle the traffic it brings. The script it is downloading from my server shouldn’t have any actual code in it. Since it is causing errors with in your script I would guess Tampermonkey isn’t passing the User Agent header when it does these requests. I’m never tested my updater in Chrome so I have no idea why it breaks. Perhaps you could try and install NinjaKit instead."
What URL are you testing this on? I tested on http://veekun.com/dex/gadgets/stat_calculator.
Anyway, the script behavior, vis à vis the menu commands did seem erratic with Tampermonkey. I couldn't really tell / didn't really check if the rest of the script was working as it should.
The culprit seems to be the sizzlemctwizzle.com update check. Removing its // #require made the menu stable. Putting that directive back, broke the script again.
I've never been a fan of that update checker, so I'm not going to dive into why it appears to be breaking the Tampermonkey instance of this script. (That would be another question -- and one probably best directed at the 2 responsible developers.)
For now, suggest you just delete it. Your users will check for updates as needed :) .

Categories

Resources