I want to use the method extension of jQuery in Rails.

Asked 2 years ago, Updated 2 years ago, 133 views

I would like to use the function here to handle the hidden attribute in HTML5, but the method extension of jQuery did not work.

https://jsfiddle.net/jhfrench/g8Sqy/

$('button').click(function(){
    $('#myElement').toggle(function(){
        if($(this).css('display')==='none'){
           $(this).prop('hidden','hidden');
        }
        else
        {
           $(this).removeProp('hidden');
        }
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<pid="myElement">Hither</p>
<button>Give it a whirl</button>

First of all, confirm that if you write directly as follows, it will work as expected

$('#myElement').toggle(function(){
        if($(this).css('display')==='none'){
           $(this).prop('hidden','hidden');
        }
        else
        {
           $(this).removeProp('hidden');
        }
 });

Then create the following file named app/assets/javascripts/toggleHide.js

jQuery.fn.extend({
    toggleHide:function(){
        if($(this).css('display')==='none'){
            $(this).prop('hidden','hidden');
        }
        else{
            $(this).removeProp('hidden');
        }
    }
});

And I changed the call to $('#myElement') .toggleHide(); but it didn't work.

What should I do if I want to add a method to jQuery in Rails?

javascript ruby-on-rails jquery

2022-09-30 21:17

1 Answers

I think Rails is irrelevant in this case.

The difference between toggle and extended method versions is
The toggle version runs the callback function after .hide() is animated.
The extended method version does not have that behavior, so the conditions are exactly the opposite (not running .hide() or display:none).
So,

jQuery.fn.extend({
    toggleHide:function(){
        if($(this).css('display')==='none'){
            $(this).removeProp('hidden');
        }
        else{
            $(this).prop('hidden','hidden');
        }
    }
});

If you write like this, you will have to toggle the hidden attribute display.
I'm sorry if I misunderstood the action I wanted to do.

<html>
<head>
<title>SAMPLE</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
jQuery.fn.extend({
    toggleHide:function(){
        if($(this).css('display')==='none'){
            $(this).removeProp('hidden');
        }
        else{
            $(this).prop('hidden','hidden');
        }
    }
});
</script>
</head>
<body>
<pid="myElement">Hither</p>
<button>Give it a whirl</button>
<script>
$('button').click(function(){
	$('#myElement').toggleHide();
})</script>
</body>
</html>


2022-09-30 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.