Optimizing code to define variables only once, code only works when the vars are in change function


<strong>Pretty sure I know the solution... would write .on('change','load', function(){} correct?</strong> <-- Tested didn't work? so I am up to your solutions :)

<em>Sushanth -- && adeneo both came up with great solutions, this is a good lesson in optimizing code... It's gonna be hard to choose which answer to go with, but I know this is going to help me rethink how I write... I dont know what I do without this forum, id have to learn this stuff in college.</em>

This is purely a question out of curiosity and bettering my skills, as well as giving you guys a chance to display your knowledge on jQuery. Also to prevent any sloppy writing.

I have a radio based switch box, the markup looks like this, the id's and on/off values are generated by the values in my array with PHP...

<span class="toggle-bg">//This color is the background of the toggle, I need jQuery to change this color based on the state on/off <input type="radio" value="on" id="_moon_page_header_area1" name="_moon_page_header_area">//this is my on value generated by the array <input type="hidden" value="_moon_page_header_area" class="switch-id-value">// I create this input because I have multiple checkboxes that have the ID _moon_ARRAYVALUE_area1 <input type="radio" value="off" id="_moon_page_header_area2" name="_moon_page_header_area">// off value <input type="hidden" value="_moon_page_header_area" class="switch-id-value">//_moon_ARRAYVALUE_area2 <span class="switch"></span>// the switch button that changes </span>

Hope that makes sense and the comments are clear

Here is the jQuery

var value = $('.toggle-bg input.switch-id-value').val() var moon1 = $('#'+value+'1').is(':checked'); var moon2 = $('#'+value+'2').is(':checked'); var static_slide = $('._moon_staticarea_height'); var toggle = $('.toggle-bg'); if(moon1){ toggle.css({'background-color': '#46b692'}); static_slide.hide() } else if (moon2){ toggle.css({'background-color': '#333'}); static_slide.show() } $('.toggle-bg').change(function () { var value = $('.toggle-bg input.switch-id-value').val() var moon1 = $('#'+value+'1').is(':checked'); var moon2 = $('#'+value+'2').is(':checked'); var static_slide = $('._moon_staticarea_height'); var toggle = $('.toggle-bg'); if(moon1){ toggle.css({'background-color': '#46b692'}); static_slide.slideUp() } else if (moon2){ toggle.css({'background-color': '#333'}); static_slide.slideDown() } });

it looks longer than it really is, its just repeating it self, one is on load so that it gives the correct color on load of the page, and then inside the change function we need to change colors..

How do I write it so I only have to use variables one time (so its cleaner) is there a better way to optimize it... Just NOW thinking after writing this I could put it in one function .on('load', 'change', function() {}

I just now thought of that, but I wrote all this so I am going to see what others think...


You'd do that by having the function in the change event handler, and on the end you chain on a trigger('change') to make it work on pageload :

$('.toggle-bg').on('change', function () { var value = $('.toggle-bg input.switch-id-value').val(), moon1 = $('#' + value + '1').is(':checked'), slider = $('._moon_staticarea_height'), toggle = $('.toggle-bg'); toggle.css('background-color', (moon1 ? '#46b692' : '#333')); slider[moon1?'slideUp':'slideDown'](); }).trigger('change');

As radiobuttons can't be unchecked, it's either moon1 or moon2, which means checking one of them should be enough.



supposed to be

// Remove the comma separator if you want to bind the same handler to // multiple events.

.on('change load',

And you can remove the one separately written out and enclose it in a function (if multiple instances of the class toggle-bg)

or just trigger the change event.(If there is a single instance of a class)

This will just run the same functionality when the page loads.

var toggle = $('.toggle-bg'); toggle.change(function () { var value = $('input.switch-id-value', this).val(), moon1 = $('#' + value + '1').is(':checked'), moon2 = $('#' + value + '2').is(':checked'), static_slide = $('._moon_staticarea_height'); if (moon1) { toggle.css({ 'background-color': '#46b692' }); static_slide.slideUp() } else if (moon2) { toggle.css({ 'background-color': '#333' }); static_slide.slideDown() } }).change();


  • How to select a statement from database?
  • [PHP]: Logic with date differences
  • Print Javadoc Summary only
  • Avoiding redundancy in updating an object's properties
  • Unable to get dirtyPropertyNames properties values for association fields in grails
  • Very Basic JS Coding, and SoundManager2 or not?
  • How do I recusively unzip nested ZIP files?
  • How can I organize this data into the objects I want with LINQ?
  • if some function is not optimized does it mean that all functions where it is declared are not optim
  • R sqldf renaming a field in a select statement
  • Changing media screen makes div overlay
  • Available space left on drive - WinAPI - Windows CE
  • Recording values of radio buttons in ember
  • Flash radiobutton: how do I get the selected radiobutton?
  • Consuming a WCF service in a Java Client using wsHttpBinding
  • Azure table store snapshot/backup capability
  • Hide HTML elements without javascript, only CSS
  • How do I display a dialog that asks the user multi-choice questıon using tkInter?
  • Bash if statement with multiple conditions
  • How to make JSON.NET deserialize to Microsoft Date Time?
  • SAXReader not re-ecape characters
  • How to get current document uri in XSLT?
  • Copy to all folders batch file?
  • Tamper-proof configuration files in .NET?
  • How can I set a binding to a Combox in a UserControl?
  • SharedPreferences or SQLite Database?
  • Ajax calls do not work in IE unless you fiddle with security settings
  • Keep this build forever option - Jenkins
  • Use of this Javascript
  • Moving mysql files across servers
  • C++ Partial template specialization - design simplification
  • How to show dropdown in excel using jrxml (jasper api)?
  • jQuery tmpl and DataLink beta
  • How to get next/previous record number?
  • How to disable jQuery.jplayer autoplay?
  • Python: how to group similar lists together in a list of lists?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • CSS Applying specific rule for a specific monitor resolution with only CSS is posible?
  • How do you join a server to an Active Directory (domain)?
  • Setting background image for body element in xhtml (for different monitors and resolutions)