Javascript Thumbs up/down - javascript

I have the following javascript, which is linked to a thumbs up and thumbs down button. When each is click the other turns off. This works perfectly. However the localstorage part doesn't
At the moment, when i refresh the page both buttons come 'on' (their active state colour)
I was trying to use removeItem so that when a button is pressed the localstorage for the other is forgotten and it won't show. However they both still come one.
Any ideas
Updated; Changed to ThumbStatus
function thumbsup(){
document.getElementById("thumbsup").classList.remove("btn-default")
document.getElementById("thumbsup").classList.add("btn-success")
document.getElementById("thumbsdown").classList.remove("btn-danger")
document.getElementById("thumbsdown").classList.add("btn-default")
localStorage.setItem('ThumbStatus',up);
localStorage.removeItem('ThumbStatus', down);
}
function thumbsdown(){
document.getElementById("thumbsdown").classList.remove("btn-default")
document.getElementById("thumbsdown").classList.add("btn-danger")
document.getElementById("thumbsup").classList.remove("btn-success")
document.getElementById("thumbsup").classList.add("btn-default")
localStorage.setItem('ThumbStatus',down);
localStorage.removeItem('ThumbStatus', up);
}
function Loadthumbs1() {
//if something was already saved....
if ( localStorage.getItem('ThumbStatus', up) )
{
var up = localStorage.getItem('ThumbStatus', up);
}
document.getElementById("thumbsup").classList.add("btn-success")
}
function Loadthumbs2() {
if ( localStorage.getItem('ThumbStatus', down) ) {
var down = localStorage.getItem('ThumbStatus', down);
}
document.getElementById("thumbsdown").classList.add("btn-danger")
}

var tu = document.getElementById("thumbsup");
var td = document.getElementById("thumbsdown");
var thumbStatus = localStorage.getItem('ThumbStatus');
function thumbsup() {
tu.classList.remove("btn-default");
tu.classList.add("btn-success");
td.classList.remove("btn-danger");
td.classList.add("btn-default");
localStorage.setItem('ThumbStatus', 'up');
}
function thumbsdown() {
td.classList.remove("btn-default");
td.classList.add("btn-danger");
tu.classList.remove("btn-success");
tu.classList.add("btn-default");
localStorage.setItem('ThumbStatus', 'down');
}
function Loadthumbs() {
if (thumbStatus && thumbStatus === 'up' ) {
thumbsup();
}
if (thumbStatus && thumbStatus === 'down' ) {
thumbsdown();
}
}

Related

Javascript not functioning when clicking the back button

I have this code in place
let showAboutSection = () => {
if(userInfo.logged && userInfo.subscriber && !userInfo.in_trial) {
let section = document.querySelector('.cbt-tabs')
if(section) {
if(!section.classList.contains('touched')) {
section.style.display = 'block'
section.classList.add('touched')
return
}
}
}
setTimeout(showAboutSection, 500)
}
showAboutSection()
But if you click on the back button or on one of my navigation tabs without refreshing the screen, it does not function. Please help!

js mousedown with touch

is there a way to detect whether a 'mousedown' is a touch right click (hold the finger about 1 sec in place) or just a normal right click?
I think chrome can do this with "ev.originalEvent.sourceCapabilities.firesTouchEvents". But only chrome.
$('#container').mousedown(function(ev) {
if (ev.button === 2 && ev.comesFromTouch) return false
//...
}
edit:
current situation: after about one second after I pressed down my left mouse button, the browser automaticly triggers a 'mousedown' event with button = 2 (tested in the 'device toolbar' mode in chrome). I want to cancel this.
SOLUTION
If a right mousedown appears between a touchstart and touchend it is a right click on a touch screen.
it works something like this.
function onPcRight() { console.log(1);}
function onTouchRight() { console.log(2);}
$('#container').mousedown(function(ev) {
if (ev.button === BUTTON_RIGHT) {
if ($(this).prop('touchdown')) onTouchRight();
else onPcRight();
}
})
.on('touchstart', function() {
$(this).prop('touchdown', true);
})
.on('touchend', function() {
$(this).prop('touchdown', false);
});
I think you can use setTimeout/clearTimeout to count 1s. The pseudo code:
var global_timer = null;
$('#container').mousedown(function(ev) {
if (ev.button === 2) {
global_timer = setTimeout(fireTouchRightClick, 1000);
}
});
$('#container').mousemove(function(ev) {
cancelTouchRightClick();
});
$('#container').mouseleave(function(ev) {
cancelTouchRightClick();
});
$('#container').mouseup(function(ev) {
if (cancelTouchRightClick() && ev.button === 2) {
fireNormalRightClick();
}
});
function cancelTouchRightClick () {
if (global_timer) {
clearTimeout(global_timer);
global_timer = null;
return true;
}
return false;
}
function fireTouchRightClick () {
global_timer = null;
// TODO touch right click
}
I also found a repo to do mouse holding on Github: https://github.com/dna2github/dna2petal/tree/master/visualization
https://github.com/dna2github/dna2petal/blob/master/samples/visualization.html
Maybe you need to pass button type to the mousehold event callback

Can't make TAB change the editor on dgrid

I'm trying to make the TAB key navigate on my dGrid. I have used as a base the solution found at Dgrid set focus on cell, but there are a couple of issues I'm running into which I couldn't solve so far.
Below you can find the block I'm using now; Not all columns have editors, so for I added a var do the element definition to select the next column instead of doing a right. I also added support for SHIFT+TAB to make backwards navigation possible. MT4.prje.grids[gridId]is the dGrid instance. There might be various on the page.
The grid is created with
MT4.prje.grids[gridId] = new (declare([OnDemandGrid, Keyboard, Selection, CellSelection]))(gridInfo, gridId);
where gridInfo has the column definitions and the store. The store is created as:
new Observable(new Memory({'data': {}, 'idProperty': 'id'}));
The editors are usually TextBox, NumberTextBox and Select dijit widgets, all set to autoSave.
aspect.after(MT4.prje.grids[gridId], "edit", function (promise, cellNode) {
if (promise === null) return;
promise.then(function (widget) {
if (!widget._editorKeypressHandle) {
widget._editorKeypressHandle = on(widget, "keypress", function (e) {
for (var rowId in MT4.prje.grids[gridId].selection) {
break;
}
for (var columnId in MT4.prje.grids[gridId].selection[rowId]) {
break;
}
if (e.charOrCode == keys.TAB) {
e.preventDefault();
var cellToEdit = null,
cellEdited = MT4.prje.grids[gridId].cell(rowId, columnId);
if (e.shiftKey) {
if (cellEdited.column.previousEditor === undefined) {
rowId = parseInt(rowId) - 1;
if (MT4.prje.grids[gridId].row(rowId).element !== null) {
for (var lastColumnId in MT4.prje.grids[gridId].columns) {}
cellToEdit = MT4.prje.grids[gridId].cell(rowId, lastColumnId);
}
} else {
cellToEdit = MT4.prje.grids[gridId].cell(rowId, cellEdited.column.previousEditor);
}
} else {
if (cellEdited.column.nextEditor === undefined) {
var firstColumnId = null;
rowId = parseInt(rowId) + 1;
if (MT4.prje.grids[gridId].row(rowId).element === null) {
var fields = {};
for (var cId in MT4.prje.grids[gridId].columns) {
if ((cId != 'excluir') && (firstColumnId === null)) {
firstColumnId = cId;
}
fields[cId] = '';
}
MT4.prje.addRowToGrid(gridId, fields);
} else {
for (var cId in MT4.prje.grids[gridId].columns) {
if (cId != 'excluir') {
firstColumnId = cId;
break;
}
}
}
cellToEdit = MT4.prje.grids[gridId].cell(rowId, firstColumnId);
} else {
cellToEdit = MT4.prje.grids[gridId].cell(rowId, cellEdited.column.nextEditor);
}
}
if (cellToEdit) {
MT4.prje.grids[gridId].deselect(cellEdited);
MT4.prje.grids[gridId].select(cellToEdit);
MT4.prje.grids[gridId].edit(cellToEdit);
}
}
});
}
});
});
Even ignoring the new line part, there are a couple of errors that happen. First of all, the editor barely pops into existence and them disappears, together with the selection. Sometimes when tabbing to an empty column, the editor will be filled with the values of the previous editor. Is there a way to do it more consistently?
What I'm figuring is that there is a race condition happening on the sharedEditor (they are set to editOn: focus). I tried wrapping the deselect/select on a dojo.on('blur') and emit it. But that doesn't get consistently correct with the dijit/form/Select widgets. Is there a better event that I can call for it?
I also tried changing the final block to:
if (cellToEdit) {
on(cellToEdit.element, 'focus', function(){
MT4.prje.grids[gridId].select(cellToEdit);
});
on(cellEdited.element, 'blur', function(){
MT4.prje.grids[gridId].deselect(cellEdited);
on.emit(cellToEdit.element, 'focus', {'bubble': true, 'cancelable': false});
});
on.emit(cellEdited.element, 'blur', {'bubble': true, 'cancelable': false});
}
But that gives two errors:
If I do make changes to a cell it does not go to the next editor. Does not even select it.
The first time I move from an empty cell to another empty cell it doesn't work either.
Anyone got any ideas?
This fix works on dgrid 0.3.11.
Add to your dgrid's postCreate.
postCreate: function() {
var that = this;
this.inherited(arguments);
this.on('dgrid-datachange', function(evt) {
that._selectedCell = that.cell(evt);
});
aspect.after(this, 'save', function(dfd) {
dfd.then(function() {
var nextCell = that.right(that.cell(that._selectedCell.row.id, that._selectedCell.column.id));
that.edit(nextCell);
// Bonus Fix. Workaround dgrid bug that blocks field text to be selected on focus.
nextCell.element.widget && nextCell.element.widget.textbox && nextCell.element.widget.textbox.select();
});
});
}

Changing Javascript to Jquery

I used to have two buttons which flicked between thumbs up and down remembered the state and loaded it on refresh. It looked like this.
var thumbStatus;
//If thumbs up is tapped change styles of each button and save to LocalStorage
function thumbsup() {
document.getElementById("thumbsup").classList.remove("btn-default")
document.getElementById("thumbsup").classList.add("btn-success")
document.getElementById("thumbsdown").classList.remove("btn-danger")
document.getElementById("thumbsdown").classList.add("btn-default")
localStorage.setItem('thumbstatus3840210', 'up');
}
//If thumbs down is tapped change styles of each button and save to LocalStorage
function thumbsdown() {
document.getElementById("thumbsdown").classList.remove("btn-default")
document.getElementById("thumbsdown").classList.add("btn-danger")
document.getElementById("thumbsup").classList.remove("btn-success")
document.getElementById("thumbsup").classList.add("btn-default")
localStorage.setItem('thumbstatus3840210', 'down');
}
//If thumbs up was the last button to be tapped, show this on page load
function Loadthumbs() {
if (localStorage.getItem('thumbstatus3840210') === 'up') {
thumbsup();
}
//If thumbs down was the last button to be tapped, show this on page load
if (localStorage.getItem('thumbstatus3840210') === 'down') {
thumbsdown();
}
}
How can I do this using Jquery. So far I have this. It only styles the buttons At the moment with no saving of data?
$(function() {
$("#thumbsup").click(function() {
$(this).addClass("thumbsup")
$("#thumbsdown").removeClass("thumbsdown")
});
$("#thumbsdown").click(function() {
$(this).addClass("thumbsdown")
$("#thumbsup").removeClass("thumbsup")
});
});
I am guessing this is what you want (your own jQuery doesn't make much sense). I wrote the function in their own place so you could edit them easily or use them in other calls, but you sure can place them directly in the click function. I also think you want to run the loadthumbs function on document ready, so I did that as well.
Also, I used an else-if function. It seems more logical to me than two if functions. Simply an else function is possible as well, but I don't know which values can be given to the item. So just to be safe an else if seems fine.
$(document).ready(function () {
function thumbsup() {
$("#thumbsup").removeClass("btn-default").addClass("btn-success");
$("#thumbsdown").removeClass("btn-danger").addClass("btn-default");
localStorage.setItem('thumbstatus3840210', 'up');
}
function thumbsdown() {
$("#thumbsdown").removeClass("btn-default").addClass("btn-success");
$("#thumbsup").removeClass("btn-danger").addClass("btn-default");
localStorage.setItem('thumbstatus3840210', 'down');
}
function Loadthumbs() {
if (localStorage.getItem('thumbstatus3840210') === 'up') {
thumbsup();
}
else if (localStorage.getItem('thumbstatus3840210') === 'down') {
thumbsdown();
}
}
Loadthumbs();
$("#thumbsup").click(function() {
thumbsup();
});
$("#thumbsdown").click(function() {
thumbsdown();
});
});
OR:
$(document).ready(function () {
function Loadthumbs() {
if (localStorage.getItem('thumbstatus3840210') === 'up') {
thumbsup();
}
else if (localStorage.getItem('thumbstatus3840210') === 'down') {
thumbsdown();
}
}
Loadthumbs();
$("#thumbsup").click(function () {
$(this).removeClass("btn-default").addClass("btn-success");
$("#thumbsdown").removeClass("btn-danger").addClass("btn-default");
localStorage.setItem('thumbstatus3840210', 'up');
});
$("#thumbsdown").click(function () {
$(this).removeClass("btn-default").addClass("btn-success");
$("#thumbsup").removeClass("btn-danger").addClass("btn-default");
localStorage.setItem('thumbstatus3840210', 'down');
});
});

javascript if condition not working?

I am sitting like hours in front of the following code snippet and can not get it running like I want.
Basically this code creates a navigation menu on right click, but a click on the switcher should turn off this function and on the next click it gets turned on again.
Everything works fine (like expected), just the little if statement on line 12 ( if ( switcher % 2 == 0 ) ) does not work like expected, meaning the code within it always gets executed whether var switcher is even or not even. I also tried other conditions like "> 0" and so on but the code within it always gets executed.
$(document).ready(function () {
/* Set switcher to zero */
switcher = 0;
/* If switch gets clicked increment var switcher*/
$('#guidenavschalter').click(function () {
switcher++;
return false;
});
/* If var switcher is even execute following code, if not do nothing of this*/
if (switcher % 2 == 0) {
/* do not display right click browser menu */
document.oncontextmenu = function () {
return false;
};
/* if click within #page excluding area of #newid */
$('#page:not(#newid)').mousedown(function (e) {
/* if right click */
if (e.button == 2) {
/* if #newid already exist display it again */
if ($('#newid').length) {
$('#newid').css({
"display": 'block'
});
$('#newid').css({
"top": e.pageY + 'px'
});
$('#newid').css({
"left": e.pageX + 'px'
});
/* if it does not exist create and display #newid */
} else {
var $div = $('#block-bookoblock-book-outline').clone().attr('id', 'newid');
$('body').append($div);
$('#newid').css({
"top": e.pageY + 'px'
});
$('#newid').css({
"left": e.pageX + 'px'
});
$('#newid').css({
"position": 'absolute'
});
return false;
}
}
/* if left click hide #newid */
if (e.button == 0) {
$('#newid').css({
"display": 'none'
});
}
return true;
});
}
});
Your code basically is
switcher = 0;
... some irrelevant code here (the callback is not executed right now)
if ( switcher % 2 == 0 ) {
So no wonder the test always pass.
What you probably want is to put the if inside the callback, so that it's tested each time you click :
var switcher = 0;
$('#guidenavschalter').click(function(){
switcher++;
if ( switcher % 2 == 0 ) {
...
}
return false;
});
switcher = 0; // created outside the click event handler
and you're increment the value inside click event handler. Therefore it is always zero.
You should go through Scoping in JavaScript
From comment, you're interested to know more about variable scope in Javascript then
check out this SO answer
I don't think it is the condition switcher % 2 == 0 that is problematic here.
You have hooked events in case of true but is there an Else statement that unhooks those events so that the original functionality is resumed? i.e. Right click create default context menu.
Update:
In order to resume original functionality, call
document.oncontextmenu = null;
in else part.
Also, you need to define $('#page:not(#newid)').mousedown(function (e) { only once (outside of if/else ) and then use the switcher variable to determine whether to call the functionality or not.
In short, you need the following
$(document).ready(function () {
/* Set switcher to zero */
switcher = 0;
/* If switch gets clicked increment var switcher*/
$('#guidenavschalter').click(function () {
switcher++;
return false;
});
document.oncontextmenu = function() {
if ( switcher % 2 == 0 ) {
return false;
} else {
return true;
}
};
/* if click within #page excluding area of #newid */
$('#page:not(#newid)').mousedown(function (e) {
if (switcher % 2 == 0) {
// do stuff
} else {
// do nothing
}
});
});

Categories