简体   繁体   中英

how to toggle certain jquery effects with javascript

I want to be able to toggle certain effects in jquery by using javascript, is this code correct? and what would be the simplest solution?

Ps dont say "use .toggle()", there is currently a bug with it that causes it to minimise the paragraph

HTML

<!--This first line calls in jquery-->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<p>Hello all</p>

CSS

p {
    color: red;
    background-color: lightblue;
    border-radius: 5px;
    height: 50px
}

JQUERY/JAVASCRIPT

var num = 0;

$(document).ready(function () {
    $("p").click(
    if (num == 0) {
        var num == 1;
    } else {
        var num == 0;);

    $("p").click(function () {
        if (num == 1) {
            $(this).animate({
                color: "black",
                backgroundColor: "white",
                fontFamily: "arial",
                fontSize: "20px",
                fontFamily: "serif"
            }, 500);
        } else {
            $(this).animate({
                color: "red",
                backgroundColor: "lightblue",
                borderRadius: "5px",
                height: "50px",
            }, 500);
        });
    });

Thank you all for your time i really appreciate it.

The easiest way to do that is probably with a data attribute as a flag, and with ternarys in the object, like this

$('p').on('click', function() {
    var flag = $(this).data('flag');

    $(this).animate({
        color           : flag ? "red"     : "black",
        backgroundColor : flag ? "#ADD8E6" : "white",
        fontSize        : flag ? "20px"    : "10px",
        borderRadius    : flag ? "5px"     : "0px"
    });

    $(this).data('flag', !flag);
});

FIDDLE

As to why your code is not working, you are just using the wrong operators in your first click handler and not defining a function, the right code should be:

var num=0;

$(document).ready(function () {

$("p").click(function(){
    if (num == 0) {
        num = 1;
    } else {
        num = 0;
    }
});

$("p").click(function () {
    if (num == 1) {
        $(this).animate({
            color: "black",
            backgroundColor: "white",
            fontFamily: "arial",
            fontSize: "20px",
            fontFamily: "serif"
        }, 500);
    } else {
        $(this).animate({
            color: "red",
            backgroundColor: "lightblue",
            borderRadius: "5px",
            height: "50px",
            fontSize: "12px",
        }, 500);
    }
});

});

However I much prefer @adeneo's solution as it's more elegant and less verbose

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