Safira
Safira

Reputation: 275

Making JavaScript not work when clicked for the second time

I have this code:

<form method="get" >
   <input type="text" name="keyword" id="map">
   <img src="style/keyboard.png" id="click"/>
   <button type="submit">Search</button> 
</form> 

And this javascript thing, adopted from here, whose job is showing the virtual keyboard when the img is clicked:

$('‪#‎map‬').keyboard({
layout: 'custom',
customLayout: {
'default': [ 
    '\u0192(h):lower_case_function_(type_h) \n\
    \u0393(h):lower_case_gamma_(type_h) \n\
    \u0394(h):lower_case_delta_(type_h)\n\ 
',
'{shift} {accept} {cancel}'
],
'shift': [
    '\u03C6(h):lower_case_phi_(type_h) \n\
    \u03C7(h):lower_case_chi_(type_h) \n\
    \u03C8(h):lower_case_psi_(type_h) \n\ 
',
'{shift} {accept} {cancel}'
]
},
usePreview: false,
openOn:null
})
.addTyping();
$('‪#‎click‬').click(function() {
$('#map').getkeyboard().reveal();
});

They work fine. But,

The problem is when the img is clicked for the second time, it doesn't hide the virtual keyboard. What I want is when the img is clicked, the keyboard appears. When it's clicked again (twice), the keyboard disappears. When it's clicked for the third time, the keyboard reappears.

How do I do that? I've googled for this issue and still have no idea what to do. Thanks..

EDITED: *Solved by using answer from @Arjun Vachhani*

$("#click").toggle(
    function()
    {
        $('#map').getkeyboard().reveal();
    },
    function() {
        $('#map').getkeyboard().close();
    });

Upvotes: 0

Views: 236

Answers (2)

speti43
speti43

Reputation: 3046

If the HTML is changing after the first click, this won't work at second time:

$('‪#‎click‬').click(function() {...

Try to use jquery .on(), beacuse the click works when the element is in DOM.

add an Id to your form:

$("‪form#myform‬").on("click","img#‎click",function() {...

or just:

 $("‪form").on("click","img#‎click",function() {...

Jquery .on()

First time triggers both, but second time only the .on() works.

Jsfiddle

Upvotes: 0

Arjun Vachhani
Arjun Vachhani

Reputation: 1958

you can use jquery toggle

$("#id").toggle(
     function () 
     {
          alert("action 1");
     },
     function () {
          alert("action 2");
     });

just paste code in first function that should handle the odd number of click event and paste code in second function that handles even number of clicks it will work

Upvotes: 1

Related Questions