snow snow - 3 months ago 14
Javascript Question

javascript: stop a function from running

I want to implement a functionality in my wikipedia app which gives the user two options:


  • an option to do an instant search, i.e. get results as the user types in the search box

  • an option to do a normal serach upon hitting
    Enter
    . i have a button to toggle that functionality. Below is the JS code:

    var btn = $(".autocomplete-button .btn")
    btn.click(searchOptions);

    function searchOptions() {

    btn.html() === "Instant Results Off" ?
    btn.html("Instant Results On") :
    btn.html("Instant Results Off");

    if( btn.html() === "Instant Results On") {
    advancedSearch();
    onSubmit();
    } else {
    onSubmit();
    }
    };


    function advancedSearch() {

    $("#wiki-search").keyup(function(e){
    getArticles();
    });


    }

    onSubmit();

    function onSubmit(){

    $(".search-form").submit(function(e) {
    e.preventDefault()
    getArticles();
    });


    }



You can test out the app here: Codepen

Problem: The default search method is a normal search. Once i turn the
instant search on
the app always does an instant search no matter what the current setting is.

What have i tried? i assumed the
advancedSearch
function keeps running regardless of what setting the button displays. Therefore i included a conditional to
return
the function whenever the button is clicked. But that didn't solve anything.

Please note the console messages. the console.log statements that i have placed in each function clearly convey that the
advancedSearch
function is correctly not being triggered when the instant search button is set to off and thats what makes this behavior so puzzling to me.

any solutions to this problem will be appreciated. I will change the title of the qn once the reason of the problem will be known. Thank you for your patience.

Answer

Just add a switch variable like this:

var liveSearchSwitch = 0;

and, make some simple logic changes.

OK, I made it:

https://codepen.io/mgolshan/pen/BLBEdR

You can see the difference with JavaScript code and mine here:

https://www.diffnow.com/?report=25eyh

Please let me know if you couldn't get what I did