0

I have a javascript code that works by removing the first and the last line of it.

Please take a look at JSFiddle

for people who wants to see it in here, here is my html:

<input id="search" onclick="search()" type="button" value="Search"/>

my javascript :

    function search() {
var search = document.getElementById('search');

var int = setInterval(function() {
    if (search.value.length == 6)
        search.value = 'Searchi';
    else if (search.value.length == 7)
        search.value = 'Searchin';
    else if (search.value.length == 8)
    search.value = 'Searching';
    else {
        search.value= 'Search';
            }
    //clearInterval( int ); // at some point, clear the setInterval
}, 500);

}

I want the function to work only when I click the button.

2
  • See .. it works :jsfiddle.net/subTZ/61 Commented Dec 17, 2012 at 8:22
  • 1
    Select "no wrap (head)" in jsFiddle, solved. Commented Dec 17, 2012 at 8:22

1 Answer 1

2

You've selected jQuery in jsfiddle.net which by default causes the site to wrap your whole code in a document.ready handler.

The result is that your search function becomes a local function within that wrapper, and not a global variable as required by a DOM0 onclick handler.

Set the jsfiddle options to "no wrap (body)" and "No-Library (pure js)" to turn off that functionality.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the tip and it worked in the JSFiddle website. but I cannot manage it to work in a normal HTML document. Is there certain objects that I need to fix inside the HTML document?
@shnisaka I can't see anything obviously wrong with the code, although putting JS event handlers inside an onclick attribute is considered very old fashioned these days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.