简体   繁体   中英

Using jQuery slideToggle when javascript is enabled instead of css display:block

I want a div with checkboxes to be displayed when mouse is hovered over button. I want jQuery code to be executed if javascript is enabled in browser. I have written CSS code for hover as work around if javascript is disabled. But CSS code always overrides jQuery code. How to achieve what I want.

The html code is as follows

<div id="button_div">
    <button id="hover_button" type="button">Select Options</button>
    <div id="checkbox_div">
        <form>
            <input id="one" type="checkbox" value="one" />
            <label for="one">One</label>
            <br />
            <input id="two" type="checkbox" value="two" />
            <label for="two">Two</label>
            <br />
            <input id="three" type="checkbox" value="three" />
            <label for="three">Three</label>
            <br />
            <input id="four" type="checkbox" value="four" />
            <label for="four">Four</label>
            <br />
        </form>
    </div>
</div>

CSS is

#button_div {
    width: 120px;
}
#hover_button {
    width: 120px;
}
#checkbox_div {
    display: none;
    position: relative;
    top: -26px;
    font-family: Verdana, sans-serif;
    background-color: #EEEEEE;
    width: 200px;
}
#button_div:hover>#checkbox_div {
    display: block;
}

jQuery code is

$(document).ready(function () {
    $("#button_div").hover(function () {
        $("#checkbox_div").slideDown("slow");
    });
});

This is the fiddle link: http://jsfiddle.net/LdzPE/

One way would be to add a class to your button_div element, say jscheck . Then in your CSS, change the rule to target that new class.

So change #button_div:hover>#checkbox_div to #button_div.jscheck:hover>#checkbox_div .

Finally, in your jQuery, remove the class. That way, if JavaScript is enabled, the class gets removed and the CSS won't be applied. However if JavaScript isn't available, the class remains and the CSS works.

jsFiddle example

What others have said is correct.

Essentially you need to bind a class to the element that has the hover effects applied to it, eg no-js , and remove it when JavaScript is loaded, if it does.

Simple changes really.

HTML

<div id="button_div" class="no-js">

JavaScript

$(document).ready(function () {
    var $btnDiv = $("#button_div");

    $btnDiv.removeClass('no-js');
    $btnDiv.not('.no-js').hover(function () {
        $("#checkbox_div").slideDown("fast");
    });
});

CSS

#button_div.no-js:hover>#checkbox_div {
    display: block;
}

Here is a fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM