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');
});
});
Related
I want to show div whose id is deliveryto1 when if condition is true it doesn't show deliverto1 div. This div(#deliverto1) is always showing in else part.
$('#delivery').change(function () {
if ($(this).val() == 1) {
$('#deliverto1').show();
$('#deliverto').hide();
} else {
$('#areas').show()
$('#deliverto').show();
}
});
You forgot to hide div in else part. Use .hide() in else part as shown below
$('#delivery').change(function () {
if ($(this).val() == 1) {
$('#deliverto1').show();
$('#deliverto').hide();
} else {
$('#areas').show()
$('#deliverto').show();
$('#deliverto1').hide();
}
});
I have created two functions. To keep it simple lets take for an example the following:
I got functions firing different events for the same objects. You can activate them using your keyboard arrows
$("body").keydown(function(e) {
if (event.which == 39) open_second_layer();
});
$("body").keydown(function(e) {
if (event.which == 37) open_first_layer();
});
As soon as I have fired one function and press the same key again it fires the animation one more time (unnecessarily).
Because of that as soon as the function open_second_layer has been fired, it should not be able to be fired again, until open_first_layer is fired again. The same should be the case the other way round.
I found .bind and .when as possible solutions, but can't figure out how to use them the right way for that case. I appreciate every suggestions or keywords to google.
You can keep a state variable and track when changes are made to it:
var state_changed = (function() {
var current = null;
return function(state) {
if (state == current) {
return false;
}
current = state;
return true;
};
}());
function open_first_layer()
{
if (!state_changed(1)) {
return;
}
// rest of code
}
function open_second_layer()
{
if (!state_changed(2)) {
return;
}
// rest of code
}
$("body").keydown(function(e) {
if (event.which == 39) {
open_second_layer();
} else if (event.which == 37) {
open_first_layer();
}
});
You can use jQuery's one().
In your first click handler, you bind the second one.
In your second click handler, you bind the first one.
sample
<div id=activate-first>first</div>
<div id=activate-second style="display:none;">second</div>
$(document).ready(function () {
function slide_first(){
$('#activate-first').show();
$('#activate-second').hide();
$('#activate-second').one('click', slide_first);
};
function slide_second(){
$('#activate-first').hide();
$('#activate-second').show();
$('#activate-first').one('click', slide_second);
};
$('#activate-first').one('click', slide_second);
$('#activate-second').one('click', slide_first);
});
Put the other function inside slide_first, like:
function slide_first(){
// other code
$('#activate_second').one('click', slide_second);
}
$('#activate_first').one('click', slide_first);
or use an Anonymous function to do the same:
$('#activate_first').one('click', function(){
// slide_first code here
$('#activate_second').one('click', function(){
// slide_second code here
});
});
Maybe your really want:
function recursiveSlider(){
$('#activate_first').one('click', function(){
// slide_first code here
$('#activate_second').one('click', function(){
// slide_second code here
recursiveSlider();
});
});
}
recursiveSlider();
This is a perfect use case for delegation. You have a single click event, and whenever the event happens, you determine what has been clicked, and you take action accordingly:
$(document.body).on("click", function(ev) {
var $targ = $(ev.target);
if ($targ.is('#button_1')) {
// someone clicked #button_1
}
if ($targ.is('.page-2 *')) {
// something inside of .page-2 was clicked!!
}
});
UPDATE: now the OP has included more code, I'm not sure the issue is - there's no need to bind and unbind events...
http://jsfiddle.net/ryanwheale/uh63rzbp/1/
function open_first_layer() {
$('#first_panel').addClass('active');
$('#second_panel').removeClass('active');
}
function open_second_layer() {
$('#first_panel').removeClass('active');
$('#second_panel').addClass('active');
}
// one event === good
$("body").keydown(function(e) {
if (event.which == 39) open_second_layer();
if (event.which == 37) open_first_layer();
});
... or if you're trying to build a slider, I suggest changing your naming convention:
http://jsfiddle.net/ryanwheale/uh63rzbp/2/
var current_layer = 1,
$all_layers = $('[id^="panel_"]'),
total_layers = $all_layers.length;
function move_layer (dir) {
current_layer += dir;
if (current_layer < 1) current_layer = total_layers;
else if (current_layer > total_layers) current_layer = 1;
$all_layers.removeClass('active');
$('#panel_' + current_layer).addClass('active');
}
// one event === good
$("body").keydown(function(e) {
if (event.which == 39) move_layer(1);
if (event.which == 37) move_layer(-1);
});
move_layer(0);
i have something being done when a radio is checked, however, now i want to make the same thing happen on page load, hopefully without duplicating the bulk of the code.
the reason i'm adding it for page load is because i'm creating an edit/update page. the first page is for saving form data to mysql database, and second page grabs values from database and displays the form as it was saved and a person can make changes and save it back to the database.
so i have this for the click. it's more than this for the other radio values, but don't want to paste too much. this is just example:
$("input[name='typeofmailerradio']").click(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
so i did a test and put all of this into the page code:
$("input[name='typeofmailerradio']:checked").val(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
first, that's what i meant by duplicating the bulk of code, and second it didn't really work. it worked for page load, but the section of code for clicking didn't want to work anymore.
what i want to do is an "or" or something. something like this, but don't know how to go about it:
$("input[name='typeofmailerradio']").click(function() || $("input[name='typeofmailerradio']:checked").val(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
by the way, what the proposed solution i wrote doesn't work at all. doesn't work on load and doesn't work when clicking.
doesn't work:
$("input[name='typeofmailerradio'],input[name='typeofmailerradio']:checked").click(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
doesn't work:
$("input[name='typeofmailerradio'],input[name='typeofmailerradio']:checked").val(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
this is what i did to make it work...
$(document).ready(function() {
function typeOfMailer() {
if($('#typeofmailerradio1').is(':checked')) {
$('#typeofpostcardmaileroptions').show("fast");
$('#snapapartoption').hide("fast");
$('#typeofspecialtymaileroptions').hide("fast");
$('#typeofmaileroptions').hide("fast");
}
else if($('#typeofmailerradio2').is(':checked')) {
$('#typeofpostcardmaileroptions').hide("fast");
$('#snapapartoption').show("fast");
$('#typeofspecialtymaileroptions').hide("fast");
$('#typeofmaileroptions').hide("fast");
}
else if($('#typeofmailerradio3').is(':checked')) {
$('#typeofpostcardmaileroptions').hide("fast");
$('#snapapartoption').hide("fast");
$('#typeofspecialtymaileroptions').show("fast");
$('#typeofmaileroptions').hide("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
$('#snapapartoption').hide("fast");
$('#typeofspecialtymaileroptions').hide("fast");
$('#typeofmaileroptions').show("fast");
}
}
$("input[name='typeofmailerradio']").click(function() {
typeOfMailer();
});
typeOfMailer();
});
You can use multiple selectors:
$('input[name=foo],input[name=bar]:checked').whatever();
^---separate them with a comma
Try something like...
$(document).ready( function() {
function do_stuff() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
}
$("input[name='typeofmailerradio']").click(function() {
do_stuff();
});
do_stuff();
}
You can't really "reuse" anonymous functions. So define them.
Here's what I'm using
$(document).ready(function() {
$(".accept").change(function () {
if ($(this).val() == "0") {
$(".generateBtn").addClass("disable");
} else {
$(".generateBtn").remove("disable");
}
});
});
It works after you change the value, but how do I add the style to the div on load to disable?
Do I simpily juse call
$(".generateBtn").addClass("disable");
Or is there a more elegant technique
How about just triggering a change ?
$(document).ready(function() {
$(".accept").on('change', function () {
if ($(this).val() == "0") {
$(".generateBtn").addClass("disable");
} else {
$(".generateBtn").remove("disable");
}
}).trigger('change');
});
I'm guessing you meant to write removeClass and not remove, if so :
$(document).ready(function() {
$(".accept").on('change', function () {
$(".generateBtn").toggleClass('disable', this.value=='0');
}).trigger('change');
});
TL;DR - Anyone know why a click handler would only work on refresh?
If I have a function like so:
function selectState() {
$('#state-select').change(function(event) {
var state = $(this).val();
$("#vmap").find(("#jqvmap1_") + (state.toLowerCase(''))).click();
});
}
and I have that function run like so:
function setClickHandlers() {
$(document).on('click','a#reset_tracker',function(event) {
event.preventDefault();
$.get('decisiontree/reset_tracker/', function(data) {
window.location.reload();
});
});
if ($('#vmap').length !== 0) {
setTimeout(function(){
$('#vmap').bind('regionClick.jqvmap', function(event, code, region) {
$('#state-select').val(code.toUpperCase());
});
selectState(); //once the map loads, we should be able to select things, right
}, 500);
}
}
Which is then called by:
function setupSlide() {
setClickHandlers();
if ((typeof $.fn.vectorMap !== "undefined" && $.fn.vectorMap !== null) &&
$('#vmap').length !== 0) {
$('#vmap').vectorMap({
map: 'usa_en',
backgroundColor: null,
color: '#6a1912',
hoverColor: '#fdb33f',
selectedColor: '#fdb33f',
enableZoom: true,
showTooltip: true,
onRegionClick: function(event, code, region) {
event.preventDefault();
$('#state-select').val(code.toUpperCase());
}
});
}
}
Which is called by:
$(document).ready(function() {
setupSlide();
$(document).on('click','.prev', function(event) {
event.preventDefault();
loadSlide(prev_slide_url,{});
});
$(document).on('click','.next', function(event) {
event.preventDefault();
var answer;
if ($(this).hasClass('button') || $(this).hasClass('button-small')) {
answer = $(this).val();
} else if ($(this).hasClass('arrow')) {
answer = $('input[type=checkbox].answer:checked').val();
if (!answer && $('input[type=checkbox]').length > 0) {
$("p.inactive").addClass("error");
return false;
}
if ($("#vmap").length > 0) {
//for the map, the value is in the select
answer = $('#state-select').val();
if ($("#state-select").val().length === 0) {
$("p.inactive").addClass("error");
return false;
}
}
} else if ($(this).hasClass('navbutton')) {
answer = $(this).data('val');
}
loadSlide(next_slide_url,{answer: answer});
});
});
Why would the click method in SelectState only be invoked when the page that contains that function (namely, the page that has #vmap on it) is refreshed, rather than when the next or prev buttons (which have functionality defined in the document.ready block of code) are clicked? Is there something special about click handlers in this sort of context? I'm really unsure as to what is going on incorrectly.
One thing that I will add is that #jqvmap1_ refers to a path element in an SVG map, namely a map of the United States. But since it works on refresh, I don't think that it has to do with the fact that it is a path element.
Let me know if you need additional clarification for this problem. Apologies for the messy code.