Reputation: 3269
I'd like to execute a JQuery toggle function (it toggles an input field to make it accessible to the client) only if a certain condition is met. (I'm testing for the condition using JavaScript.) Can I do this? For some reason, the JQuery toggle function doesn't work when I set it inside the JavaScript function, so I'm not sure if I'm doing something wrong, or if this can't be done at all.
<script type="text/javascript">
function conditionalToggle()
{
if (conditionIsMet)
{
// JQuery toggle call here
}
}
</script>
Upvotes: 0
Views: 2011
Reputation: 5123
You can do it when DOM is ready, if you've still problem, you can do also like that:
<script type="text/javascript">
$(window).load(function() {
conditionIsMet && $('#elementId').toggle();
});
</script>
Upvotes: 0
Reputation: 150313
You probably don't use jQuery right, or don't execute the function, or (the most common mistake of new jQuery users) don't wait for the DOM to be ready:
function foo(){
if ("foo" === "foo")
$('#elementId').toggle();
}
$(function(){ // functions inside $() runs after the DOM is ready.
foo();
});
Where elementId
is a place holder to your element id.
Simple DEMO
Note that you can use this toggle
overload:
$('#elementId').toggle(showTheElementOrNot);
toggle( showOrHide )
showOrHide
A Boolean indicating whether to show or hide the elements.
Upvotes: 3
Reputation: 318352
jQuery should work if inside a ready() function
<script type="text/javascript">
$(function() {
function conditionalToggle(){
if (conditionIsMet) {
$(element).toggle();
}
}
});
</script>
or just do:
<script type="text/javascript">
function conditionalToggle() {
if (conditionIsMet) {
element.style.display = element.style.display=='block' ? 'none' : 'block';
}
{
</script>
Upvotes: 1