Search code examples
javascriptjquerycodeigniterif-statementpopover

if condition not working in bootstrap popover


I need to show some content using bootstrap popover in several conditions.

If the value of the attribute is greater than the number defined, the popover should be displaying.

But here, popover starts to display in every attribute after the condition is met.

var number = 3;
$('a').hover(    
function() {  
if($(this).attr("value") > number) {
    $(document).ready(function(){
    $('[data-toggle="popover"]').popover();        
    });
}
});
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> 
  </script>

<br>
<br><a value = "1" data-toggle="popover" data-trigger="hover" data-content="Some content 1">Hover over me 1</a>
<br><a value = "2" data-toggle="popover" data-trigger="hover" data-content="Some content 2">Hover over me 2</a>
<br><a value = "4" data-toggle="popover" data-trigger="hover" data-content="Some content 4">Hover over me 4</a>
<br><a value = "5" data-toggle="popover" data-trigger="hover" data-content="Some content 5">Hover over me 5</a>
<br><a value = "6" data-toggle="popover" data-trigger="hover" data-content="Some content 6">Hover over me 6</a>

How can I make it display the popover only when the value is greater than the number?


Solution

  • The popover api allows for a 'show' argument that can be called on a popover element.

    Its probably also good to make sure you're dealing with a number and not a string, hence parseInt the number you want to check against.

    var number = 3;
    
    $(document).ready(function(){
        $('a').hover(function() {  
          if(parseInt($(this).attr("value")) > number) {
            $(this).popover('show');
          }
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    
    <br><a value="1" data-toggle="popover" data-trigger="hover" data-content="Some content 1">Hover over me 1</a>
    <br><a value="2" data-toggle="popover" data-trigger="hover" data-content="Some content 2">Hover over me 2</a>
    <br><a value="4" data-toggle="popover" data-trigger="hover" data-content="Some content 4">Hover over me 4</a>
    <br><a value="5" data-toggle="popover" data-trigger="hover" data-content="Some content 5">Hover over me 5</a>
    <br><a value="6" data-toggle="popover" data-trigger="hover" data-content="Some content 6">Hover over me 6</a>