Turn border radius on and off with jquery click event

There are several divs. I need to change the radius of the border using the click event. I managed to change the radius of the border only once. When someone clicks on a div, the radous border should be changed to 50%, and again click on the same div, the applicable border radius should delete.

And while there is a border that changed the div, and if you click on another div border of the changed div, you need to remove it and the radius of the border should be applied to the pressed div. This means that there should be only one border radius at a time.

I have this code

jsfiddle

HTML

<div></div> <div></div> <div></div> <div></div> 

And this is css

 div { width: 100px; height: 100px; background: #000; margin: 10px; float: left; } 

also this jquery code

 $('div').each(function(){ $(this).click(function(){ $(this).css('border-radius', '50%'); }); }); 

please help me about this .. i have no idea how to do this ..

+4
source share
7 answers

Use the class for this:

Demo

 $('div').click(function(){ if($(this).is('.radius')){$(this).removeClass('radius'); return;} $(this).addClass('radius').siblings().removeClass('radius'); }); div.radius {  border-radius:50% } 
+10
source

I updated my code by adding CSS classes: http://jsfiddle.net/Hq6TQ/7/

 div.round-border { border-radius: 50%; } 

and adding it using jQuery:

 $(this).addClass("round-border"); 

PS you do not need to iterate over each div element and bind events, you can just use the following fragment:

 $('div').click(function(){ // do whatever you need here }); 

UPDATE : while here is what you originally asked, I have not read your question well.

+2
source

You might want to provide more divs than this. Therefore, you must select the class to select. I updated your code and provided you with this function:

 $('div.radius').each(function(){ $(this).click(function(){ $('div.radius').css('border-radius','0'); $(this).css('border-radius', '50%'); }); }); 

http://jsfiddle.net/C23a2/1/

+2
source
 $('div').toggle(function(){ $(this).css('border-radius', '50%'); }); 
0
source

First, you do not need to do every click event. Just click click. Then:

 $('div').click(function(){ $(this).css('border-radius', $(this).css('border-radius') == '50%' ? '0px' : '50%'); }); 

An alternative to A (better) would be to use toggleClass() , as some people have suggested.

0
source

Jquery:

 $('div').click(function () { $('div').removeClass('radius') $(this).addClass('radius'); }); 

CSS

 div.radius { border-radius:50% } 

Demo

0
source

Try it while working well.

 $('div').each(function () { $(this).click(function () { if ($(this).css("border-radius") == "0px") { $(this).css('border-radius', '50%'); } else { $(this).css('border-radius', '0'); } }); }); 

JSFIDDLE

0
source

Source: https://habr.com/ru/post/1488058/


All Articles