javascript - Correct Way to Dynamically Add Semantic UI Controls? -
i'm trying wrap head around semantic ui , understand how controlled class give dom element, can't work when adding new dom elements dynamically. seems semantic ui javascript getting run on first page load , not on new elements when add them. currently, done via:
$("#target").html("<new elements here>")
is there correct way this? cannot find documentation on semantic ui site.
update: give better example...
say have layout:
<div class="right menu" id="rightmenu"> <div class="ui dropdown link item"> courses <i class="dropdown icon"></i> <div class="menu"> <a class="item">petting</a> <a class="item">feeding</a> <a class="item">mind reading</a> </div> </div> <a class="item">library</a> <a class="item">community</a> </div> </div>
and code run:
var menu = '<div class="ui dropdown link item"> \ test \ <i class="dropdown icon"></i> \ <div class="menu"> \ <a class="item" href="http://google.com">google</a> \ <a class="item" href="http://amazon.com">amazon</a> \ </div> \ </div>'; $("#rightmenu").append(menu)
the new menu item appears fine... doesn't dropdown should, until run this:
$('.ui.dropdown') .dropdown({ on: 'hover' });
after that, opens on hover fine. there way not have rerun every time?
there few ways of adding elements dom. html
(would empty container , insert new elements) 1 of them. can use append
append new elements existing set. but, problem events not being triggered on dynamically added elements. solution event delegation. read more here.
from jquery doc: delegated events have advantage can process events descendant elements added document @ later time. picking element guaranteed present @ time delegated event handler attached, can use delegated events avoid need attach , remove event handlers.
here quick demo i'd set adding new elements, event delagation etc. hope helps.
var $container = $("#container"); var count = 3; $container.on("click", 'button', function() { alert ("you've clicked on " + $(this).text() ); }); $("#addbuttons").on("click", function() { $container.append("<button>button" + (++count) + "</button>"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <button>button1</button> <button>button2</button> <button>button3</button> </div> <button id="addbuttons">add few more!</button>
edit: dynamically adding semantic ui elements, rule remains same it's element
. not sure if there other problems on page. @ updated demos below.
1) using append
2) using html
edit: so, that's how semantic ui dropdown supposed work dropdown created/rendered javascript. therefore, when new options/dropdowns added related method ($('.ui.dropdown').dropdown({on: 'hover'});
) needs re-triggered. workaround add simple
class newly created dropdown, i.e. var menu = '<div class="ui simple dropdown link item"> \
trigger dropdown when mouseover, but. it's no animation!
hope helps.
Comments
Post a Comment