JQuery not able to get dynamic HTML element [duplicate] - javascript

This question already has answers here:
jQuery .on() event doesn't work for dynamically added element
(3 answers)
Closed 4 years ago.
I have this problem in JQuery and I can't seem to get past this issue.
I have a dynamically generated list of Li elements, and for each Li element I want to attach an On Hover so that a dropdown shows below the Li element. The catch is the Li elements are generated dynamically.
I have tried using .on("hover"), but nothing triggeres the event. The following is my code.
//On Init
$( document ).ready(function() {
generateList();
$(".app").on("hover", function () {
console.log('test'); //Does not trigger
});
$(".app").on("mouseenter", function () {
console.log('test'); //Does not trigger
});
});
//Load JSON file to generate app listing
function generateList(){
//Load JSON file
$.getJSON('json/adapters.json', function (json) {
var listCol = 5;
var ul = $('#container-apps');
//Generate app list from adapters.JSON
json.adapters.forEach(function (adapter) {
//Count adapter for no result function
adapterCount += 1;
var link = adapter.link;
var git = adapter.git;
var img = adapter.image;
var name = adapter.name;
//Appending the HTML elements
//List element
var li = $("<li>").attr("class", "app").appendTo(ul);
var a = $("<a>").attr({
"href": "javascript:void(0);",
"target":"_blank",
"class":"app-link",
}).appendTo(li);
var image = $("<img>").attr("src", img).appendTo(a);
var label = $("<div>").attr("class", "item-name black-font").html(name).appendTo(a);
//Hover element
var hoverContainer = $("<div>").attr("class", "hoverContainer").appendTo(li);
var hoverUL = $("<ul>").appendTo(hoverContainer);
var hoverPageLi = $("<li>").appendTo(hoverUL);
var hoverPageA = $("<a>").attr({"href": link, "target":"_blank", "class":"app-link"}).html("SDK").appendTo(hoverPageLi);
var hoverGitLi = $("<li>").appendTo(hoverUL);
var hoverGitA = $("<a>").attr({"href": git, "target":"_blank", "class":"app-link"}).html("Github").appendTo(hoverGitLi);
});
//Generate dummy box for responsive
for (var i = 0; i < (listCol); i++) {
$('<li class="item flex-dummy"></li>').appendTo(ul);
}
});
}
$(function () {
$(".app").hover(){
console.log('test'); //Does not trigger
}
})

Try this syntax:
$("body").on("click", ".app", function(){
//do something
});

Related

jQuery function does not work on mouseover and click state

Building a new site and trying to reuse a JavaScript from the current site that change image on hover. I have a hard time to understand JavaScript so I hope someone can help me to see what I'm missing or doing wrong.
The current site (where I copied from) has many more script running and I don't know if some other script is missing. I have tried to change the initializing part of the script to fit the new site. Please have a look at the puzzlepiece on the current page. http://www.collyfiltreringsteknik.se.
I have got the script running to a point where it adds the four "quad" divs but the mouseover and click function does not work.
This is the html code
<div id="companyvalues" class="clearfix">
<div class="valueimage"></div>
</div>
The jQuery part
(function($){
$.fn.extend({
companyvalues: function(kwargs) {
var defaults = {
static_base:''
};
var options = $.extend(defaults, kwargs);
return this.each(function() {
var obj = $(this);
var div = $('div', obj);
var topleft = $('<div class="quad topleft" data-image="i0000" data-href="/grundpelare/tillganglighet/"></div>');
var topright = $('<div class="quad topright" data-image="i0003" data-href="/grundpelare/konkurrenskraft/"></div>');
var bottomleft = $('<div class="quad bottomleft" data-image="i0002" data-href="/grundpelare/miljoforbattring/"></div>');
var bottomright = $('<div class="quad bottomright" data-image="i0001" data-href="/grundpelare/kostnadsreducering/"></div>');
obj.prepend(bottomright);
obj.prepend(bottomleft);
obj.prepend(topright);
obj.prepend(topleft);
var divs = $('div.quad', obj);
$([ '/uploads/pages/varden_0000_yellow.png',
'/uploads/pages/varden_0001_red.png',
'/uploads/pages/varden_0002_green.png',
'/uploads/pages/varden_0003_blue.png'
]).preload({base_url:options.static_base});
divs.mouseover(function(event) {
var item = $(this);
var data_image = item.attr('data-image');
div.addClass(data_image);
event.preventDefault();
event.stopPropagation();
});
divs.mouseout(function(event) {
var item = $(this);
div.removeClass('i0000');
div.removeClass('i0001');
div.removeClass('i0002');
div.removeClass('i0003');
event.preventDefault();
event.stopPropagation();
});
divs.click(function(event) {
var item = $(this);
var href = item.attr('data-href')
document.location.href=href;
event.preventDefault();
event.stopPropagation();
});
});
}
});
})(jQuery);
Initializing the script.
$(document).ready(function() {
$('#companyvalues').companyvalues();
});

Changing text inside of a dynamically created element

I want to change the text inside of an element for dynamically created elements. i = 2 because that's Why is it not working?
var loanName = function() {
for(var t=1; t < i; t++) {
$('body').on('keyup', '.loanNameV'+t, function () {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
};
$('body').on('keyup', '[class^="loanNameV"]', function () {
var numbesideclass = ($(this).attr('class').split('loanNameV'))[1];
var loanN = $(this).val();
$('.nameLoan'+numbesideclass).text(loanN);
});
Note: this code will work if you don't have another class for loanNameV elements like class="loanNameV1 anotherclass anotherclass" in this case this code will not work as expected

jQuery Tree issue - add first child li

I have 2 columns, on the left side a team with users, on the right column, will be displayed the users i have selected. so everything its working but i'm trying to implement a new feature as follow:
I have 2 list level like a tree (only 2 levels). When i click on a user, i'm able to select it sending to the right column. Also, when i click (single click) on the first level (team name), the second level (users) appear as toggle jquery function. i need so, when i double click on a team (level 1) all users on that tree turns selected and go to column on the right side.
Also, when i click on the team (first level) on the right side, all the users get removed back.
My code to add the users jquery current is:
$(document).ready(function () {
var maxAllowed = 10000;
var $selectTable = $("#mytable");
var $selectList = $("#selected_users ul")
$("#max-count").html(maxAllowed);
var getActivated = function () {
var activated = new Array();
$selectTable.find('input[type="checkbox"]:checked').closest("li").each(function () {
var $obj = new Object;
var currentBox = $(this).find('input[type="checkbox"]');
$obj.id = currentBox.val();
$obj.boxid = currentBox.attr("id");
$obj.name = $(this).find("label").text();
activated.push($obj);
});
return activated;
}
var updateActiveList = function () {
// Truncate list
$selectList.html("");
$(getActivated()).each(function () {
$selectList.append("<li><a href='#' class='remove' data-id='" + this.id + "' data-box-id='" + this.boxid + "'>" + this.name + "</li></a>");
});
}
var countActivated = function () {
return getActivated().length;
}
$('#view').click(function () {
allIds = new Array();
getActivated().each(function () {
allIds.push($(this).attr("id"));
});
alert(allIds);
});
$selectList.on("click", "a.remove", function () {
$('#' + $(this).data("box-id")).prop("checked", false);
updateActiveList();
});
$selectTable.on("change", 'input[type="checkbox"]', function (event) {
if ($(this).is(":checked") && countActivated() > maxAllowed) {
event.preventDefault();
console.log("max reached!");
$(this).prop("checked", false);
}
updateActiveList();
});
});
Here's a jsFiddle with working example:
http://jsfiddle.net/muzkle/LMbV3/7/
Thanks all!
EDIT
Hi, i just added a code to separate single click from double click. So when the user single click, will open the tree. now i need when the user double click on the first level, add both (first level and they're childrens to the right side.
Follow code for single and double clicks:
alreadyclicked=false;
$(document).ready(function () {
$('#mytable').on('click', '.toggle', function (ul) {
//Gets all <tr>'s of greater depth
//below element in the table
var findChildren = function (ul) {
var depth = ul.data('depth');
return ul.nextUntil($('ul').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var ul = el.closest('ul'); //Get <tr> parent of toggle button
var children = findChildren(ul);
var el=$(this);
if (alreadyclicked){
alreadyclicked=false; // reset
clearTimeout(alreadyclickedTimeout); // prevent this from happening
}else{
alreadyclicked=true;
alreadyclickedTimeout=setTimeout(function(){
alreadyclicked=false; // reset when it happens
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (ul.hasClass('collapse')) {
ul.removeClass('collapse').addClass('expand');
children.hide();
} else {
ul.removeClass('expand').addClass('collapse');
children.show();
}
return children;
// do what needs to happen on single click.
// use el instead of $(this) because $(this) is
// no longer the element
},300); // <-- dblclick tolerance here
}
return false;
});
});
And new jsFiddle is: http://jsfiddle.net/muzkle/LMbV3/8/
To distinguish different groups I am wrapping each group/section in a wrapper div with class .wrapper
<div class="wrapper">
.
.
</div>
Also I attached a double click event to .wrapper and currently I have made it to alert its inner labels.Just write some additional code to add these labels to the right side like you are currently adding one element on click.Below is the code with jQuery .dblclick() function which attaches a double-click event to .wrapper.
$('.wrapper').dblclick(function(){
$(this).find('label').each(function(){
alert($(this).text());
});
});
Check this fiddle

How can i optimize my Jquery code?

I've created some JavaScript using Jquery, for the page animation :
I trying to optimize it since i repeat the same thing for subtab1, subtab2, subtab3.
The same function is executed for all of them, and the only thing is changes is variable i iterating on?
Any suggestion?
<script type="text/javascript">
$(document).ready(function () {
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
var $fundosdiponiveis = $('#fundosdiponiveis');
var $fundosdiponiveisTab = $('#tabs1');
$defensivo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$defensivoSubTab.removeClass("hide");
$defensivoSubTab.show();
});
$equilibrado.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$equilibradoSubTab.removeClass("hide");
$equilibradoSubTab.show();
});
$activo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$activoSubTab.removeClass("hide");
$activoSubTab.show();
});
});
</script>
For a while:
var $fundosdiponiveis = $('#fundosdiponiveis');
This is my default div.
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
That divs apears when i clicking on one of the following tabs:
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
And that button hides and changes style"display" to none, on click, of my three #subtab's
var $fundosdiponiveisTab = $('#tabs1');
Any suggestion?
You could write a function that returns the proper function:
function createShowTabFunc(tab) {
return function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
tab.removeClass("hide");
tab.show();
}
}
Then assign your click handlers:
$defensivo.live('click', createShowTabFunc($defensivoSubTab));
$equilibrado.live('click', createShowTabFunc($equilibradoSubTab));
$activo.live('click', createShowTabFunc($activoSubTab));
Have a common class attribute to all the tab's and you just need to write $('.class').click() and in this get the id of the corresponding tab and according to the id fetched by attr function, you can have an if else to define your variables inside the if else and execute your code block.

trying to remove and store and object with detach()

I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:
How to I undo .detach()?
But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:
function MMtoggle(IDnum) {
var rowID = "row" + IDnum;
var jRow = '#' + rowID;
thisMMbtn = $(jRow).find(".addMMbtn");
var light = false;
var that = this;
if (light == false) {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
$(this).unbind("click");
light = true;
}
);
}
else {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
thisMM = thisRow.find(".mmCell");
SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
$(this).unbind("click");
light = false;
}
);
}
}
MMtoggle(g.num);
A fiddle of the problem is here: http://jsfiddle.net/pScJc/
(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)
Looking at your code I don't think so you need detach for what you are trying to achieve.
Instead try this code.
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var $mmCell = thisTxt.find('.mmCell');
if($mmCell.length == 0){
$mmCell = $('<div class = "mmCell prep"></div>')
.appendTo(thisTxt).hide();
}
$mmCell.toggle();
//$(this).unbind("click");
}
);
Demo

Categories

Resources