Question

I need to make a number, d, increase by 1 every time I click a <pre>. I have tried the onClick="javascript" and the id="id" but can't find the right code, I need to also display d above the <pre> as: "You have d objects!" I put all my javascript in <head> and my html in <body> if that's what's wrong.

Was it helpful?

Solution

<span id="counter">0</span>
<pre id="my-pre">test</pre>

<script>
    var counter = 0,
        counterSpan = document.getElementById('counter');

    //add the click listener using addEventListener, this is preferred over inline handlers
    document.getElementById('my-pre').addEventListener('click', function () {
        counterSpan.innerHTML = ++counter;
    });
</script>

However putting your scripts directly after HTML elements will quickly get messy. A better alternative would be to modularize your code.

//Create an object that represents your feature and encapsulates the logic
var CounterFeature = {
    count: 0,
    init: function (preElSelector, countElSelector) {
        var preEl = this.preEl = document.querySelector(preElSelector);

        this.countEl = document.querySelector(countElSelector);

        preEl.addEventListener('click', this.increment.bind(this));

        return this;
    },
    increment: function () {
        this.countEl.innerHTML = ++this.count;
    }
};

//wait until the DOM is ready and initialize your feature
document.on('DOMContentLoaded', function () {
    //create a new instance of the CounterFeature using Object.create
    //and initialize it calling `init`
    var counterFeature = Object.create(CounterFeature).init('#my-pre', '#counter');

   //you could also simply use the singleton form, if you do not plan to have
   //more than one CounterFeature instance in the page
   //CounterFeature.init(...);
});

OTHER TIPS

Here is my quick solution (js fiddle: http://jsfiddle.net/65TMM/)

With the html:

<pre>Add another object</pre>
<p>You have <span class="count">0</span> objects!</p>

And javascript (using jQuery):

$(function() {

    $('pre').on("click", function() {
        addOneToObjects();
    })

});

function addOneToObjects() {
    var countSpan = $('.count');
    var currentThings = parseInt( countSpan.text() );
    currentThings++;
    countSpan.text(currentThings);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top