Changing text in a div onclick

Discussion in 'JavaScript' started by OliverG, Jul 15, 2013.

  1. #1
    I hope this is the appropriate category in which to ask this question.

    I am not at all well versed in Javascript, but i believe what i'm trying to achieve should be relatively simple.

    I have two buttons (an up arrow and a down arrow), and i would like them to cycle through text numbers in a separate div when clicked. How would i go about doing this?

    My apologies if this i the incorrect format for asking a question.

    Thanks,

    Oliver
     
    OliverG, Jul 15, 2013 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    Something like this (?) :
    var current_value = 0;
    $(document).ready(function() {
    $("#div").html(current_value);
     
    $(document).delegate("#button1","click",function(){
    current_value++;
    $("#div").html(current_value);
    });
     
    $(document).delegate("#button2","click",function() {
    current_value--;
    $("#div").html(current_value);
    });
    });
    HTML:
    Be sure to include jQuery before executing the above code.
    div is the id of the place you want to show the actual value currently selected, button1 is the id of the button that does the incrementation and button2 is for the button that does the decrementation.

    Hope this helps.
     
    tvoodoo, Jul 20, 2013 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    I'd suggest skipping the jQuery asshattery and handling it with normal scripting... A GOOD script should probably add the buttons to the markup itself since scripting off they serve no purpose, wrap the setup in an anonymous function so you don't have to worry about namespace conflicts, and handle this via the DOM instead of innerHTML so it doesn't force a reflow.

    So if you had this for markup:
    <div id="changeMe"></div>
    Code (markup):
    The scripting would go something like this:
    (function(){
    
    	var
    		count = 0,
    		d = document,
    		t = d.getElementById('changeMe'),
    		n = t.nextSibling,
    		p = t.parentNode;
    		
    	t.appendChild(d.createTextNode(count));
    	
    	function tChange(value) {
    		while (t.firstChild) t.removeChild(t.firstChild);
    		t.appendChild(d.createTextNode(value));
    	}
    	
    	function makeButton(value,handler) {
    		var e = d.createElement('div');
    		e.className = 'button';
    		e.appendChild(d.createTextNode(value));
    		e.onclick = handler;
    		p.insertBefore(e,n);
    	}
    	
    	makeButton('-',function() { tChange(--count); });
    	makeButton('+',function() { tChange(++count); });
    	
    })();
    Code (markup):
    Changing the handler functions in makeButton as needed.
     
    deathshadow, Jul 20, 2013 IP