Home  >  Q&A  >  body text

How to create a clickable event: click on the same path

Hi everyone, I'm currently making a DIV that when the path to the SVG is clicked, it creates a DIV. I've got the function working, but the problem I'm having now is that when I click on another path, it just opens a new DIV instead of updating the information in the already created DIV. Here is my current JavaScript example:

var fakeObject = {"One": {"givenName": "Joshua"}, "Two": {"givenName": "James"}}

console.log(fakeObject)

$("path").on("click", function(e){
    var pathID = e.target.id.split('_');
  console.log(pathID)
  createDiv(pathID[1]);
});

function createDiv(value){
    $("#DOM").append(`
    <div>
        <p>${fakeObject[value].givenName}</p>
    </div>
  `)
}

I know my path function always fires when the path is clicked, so I'm not sure how to rewrite it to turn off the DIV when a new path is clicked, but the best case would be to just change the DIV when a new path is clicked elements in . The code for the HTML example is as follows:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <path id ="Path_One" d="M10,60 L50,10 90,60" />'
  <path id="Path_Two" d="M20,30 L10,130 20,30" />
</svg>
<div id="DOM">
  <p>
    这是一个测试DIV
  </p>
</div>

Currently, whenever a path on the SVG is clicked, it only adds a new DIV instead of updating when another object is clicked. My thought was to close the DIV when the new path is clicked and open a new one, but if the DIV could be updated with the new information, that wouldn't be necessary.

P粉426906369P粉426906369276 days ago352

reply all(1)I'll reply

  • P粉419164700

    P粉4191647002024-01-17 15:20:39

    Hey :) You can give your div an id and then use length to check if it exists. If it exists, just populate it with new content using .html.

    function createDiv(value){
          if($('#divname').length == 0){   
            $(document.createElement('div')).attr('id', 'divname')
          }
          $('#divname').html(<p>...</p>)                         
         }

    reply
    0
  • Cancelreply