I have implemented dynamic components in Angular and whenever a dynamic component is loaded its corresponding jQuery is not working. Same jQuery script is working elsewhere.
This is where my dynamic component loads:
<div class="listing-table-outer" [#myAwesomeAnimation]='state'>
<app-dynamic-question [componentData]="componentData"></app-dynamic-question>
</div>
Below html will be loaded dynamically.
<div class="panel panel-default " >
<div class="panel-body" >
<h1>{{textLabel}}</h1>
<p>{{textHeader}}</p>
<div class="form-inline display-one" role="form">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="">
</div>
<div class="learn-more magtop10">
<a> <i class=" glyphicon glyphicon-play"></i> Learn More</a>
</div>
<div class="display_advance">
<div class="well">
<p>{{textFooter}}</p>
</div>
</div>
<div class="bs-component">
Clear
Skip
Continue
</div>
</div>
</div>
I have written this script
$(document).ready(function(){
$('.learn-more').click(function() {
$('.display_advance').slideToggle('1000');
$("i", this).toggleClass(" glyphicon-play glyphicon-triangle-bottom");
});
});
I have checked this script and it is working perfectly elsewhere.
Please let me know why this is happening.
As you already stated yourself, the html is loaded dynamically. That means that this html is not yet there when $(document).ready(function() { ... }) is executed. So you're trying to add a click event to an element that doesn't exist at that moment.For this exact situation there's a thing called event delegation.
Instead of doing
$('.learn-more').on('click', function() { ... });
you would do
$(document).on('click', '.learn-more', function() { ... });
This way any elements below document with class learn-more, now or in the future, will get this click event.
Related
I have a little mini html game that uses Backbone.
The main page has multiple <div> tags with the class name of "monsterName".
There is a button near it, that, when clicked, I want to get the text that is inside the "monsterName" <div>
I am trying to use the closest() method from the WebAPI to find the closest <div> to the clicked button that has a class name of "monsterName".
Here this will help you see my HTML page generated by the view and template:
<div id="root">
<div id="title">Monster Hunting 101</div>
<div class="monsterArea">
<div class="monsterName">Orc</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
<div class="monsterArea">
<div class="monsterName">Dragon</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
<div class="monsterArea">
<div class="monsterName">Giant</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
The view has code that fires when the button ".findMonster" is clicked:
events: {
"click .findMonster": "startHunt"
},
When that button is clicked, it fires this function:
startHunt: function (e) {
const $closestMonster = e.closest('.monsterName');
console.log($closestMonster.innerHTML);
...do some stuff with the text in the monsterName...
}
So the view is working and the button works, and it fires off the startHunt event.
But it always gives me this error:
Uncaught TypeError: e.closest is not a function
A combination of closest() and find() worked for this problem:
const $closestMonster = e.closest('.monsterArea').find('.monsterName');
before all thanks for reading.
So... I have a problem with bootstrap popover. I have tried many configurations with no success, so I'll try to explain the problem as clearer as I can.
I have multiple elements within bootstrap columns and when the user click on one of them a popover comes out with a form in its popover-content.
Every form is different due to its attributes, you can choose different options in the popover and then send the form.
Untill this point everything is fine, the popover works correctly. The thing is that when I click a second time over the same element in order to hide the popover, popover hides but not the title and the next popover I click content is empty, I mean, popover content stop working, it only show titles.
I think I'm missing something but I can't find out what.
The code that load the content:
$("[data-toggle=popover]").popover({
trigger: "click focus",
template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3>⊗<div class="popover-body"></div></div>',
content: function() {
var $html = $(this).parent().find(".prod-popover").eq(0).html();
return $(".popover-content").html($html);
}
});
I've tried with trigger focus, click, manual and a mix of them with the same results.
I have also tried changing the wrapper .popover-content with #popover-content.
Code to hide popover:
$(document).on("click", "a.popover-close", function(e) {
e.stopPropagation();
$(".popover-content").popover('hide');
return false;
});
Another for hiding found here in stack overflow
$(document).click(function(e) {
if ($(".popover").has(e.target).length == 0 || $(e.target).is(".close")) {
$("#popoverId").popover("hide");
}
});
Another one:
$("[data-toggle=popover]").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
$("[data-toggle=popover]").not(this).popover('hide');
});
HTML:
<div class="col-md-6 col-sm-6 col-xs-12 bt-border k-item" data-placement="right" data-toggle="popover" data-title="Whatever" data-container="body" data-html="true">
<div class="hidden prod-popover">
<form class="cart" role="form" method="post" action="">
<div class="form-group">
<label>Label</label>
<textarea rows="2" placeholder="PLACEHOLDER"></textarea>
</div>
<div class="form-group">
<div class="btn-group pop-quantity" role="group">
<input type="text" value="1" min="1" step="1">
</div>
</div>
<button type="button">Send<button>
</form>
</div>
<div class="row">
<div class="col-md-2 col-sm-2 col-xs-2"><img src="SRC" alt=""></div>
<div class="col-md-8 col-sm-8 col-xs-8">
<h4 class="no-pad-bt">Whatever</h4>
<p class="no-pad-bt">Description</p>
</div>
<div class="col-md-2 col-sm-2 col-xs-2 text-right">
<p>Price</p>
</div>
</div>
Any help will be highly appreciated.
I have an ng-repeat repeating some data from my table and on each card there's a button you can press, I want this button to just make an alert when you press it and this is my current code:
<div class="row" ng-repeat="data in ids">
<div class="row">
<!--<div class="col s12 m6">-->
<center>
<div class="flipcard">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<p>{{data.amount}} coin wager with {{data.posted_nickname}}
<a id="joinflip" class="right waves-effect waves-light btn"><i class="material-icons left">games</i>Play</a> </div>
</div>
</div>
</center>
</div>
</div>
And this is my JavaScript:
$(document).ready(function () {
$("#joinflip").click(
function () {
alert("Alert Message OnClick");
}
);
});
The button works outside of the ng-repeat loop but when within ng-repeat it never triggers the onclick, thanks for any help
That's because ng-repeat elements are created after document fired 'ready' event. You should use ngClick instead.
The problem is because the DOM is not ready yet.
you need to use event delegation (you need to use a class instead of an ID because they will repeat)
$(document).on("click", ".joinflip", function() {
console.log("clicked");
});
Hope it help :D
What is the proper way to re-apply jquery to objects which are cloned??
I have an example I rigged up in jsfiddle here: http://jsfiddle.net/49o6arLu/16/
<div class="hidden element-holder">
<div class="element">
<div class="button">Button</div>
<div class="green-square"></div>
</div>
</div>
<div class="element">
<div class="button">Button</div>
<div class="green-square"></div>
</div>
<div class="clear"></div>
<div class="add-element">Add Element</div>
$('div.button').click(function(event) {
if($(this).parent().children('.green-square').is(':visible')) {
$(this).parent().children('.green-square').hide();
}else{
$(this).parent().children('.green-square').show();
}
});
$('div.add-element').click(function(event) {
$('div.element-holder').children('div').clone().insertAfter($('div.element-holder'));
});
As you can see, the initial displayed box and button work just fine. However, When you add another element the new element button does not work anymore.
I understand why I have this problem, however I don't know the proper way I should go about re-applying the Jquery to the new elements which are cloned.
Can someone provide a solution to the jquery and provide some explanation as to what you did?
Thanks!
You can save the need to re-apply the handler to all the appended elements by having a single delegated click handler on a common parent element.
First of all amend your HTML to include the container, in this case #element-container:
<div class="hidden element-holder">
<div class="element">
<div class="button">Button</div>
<div class="green-square"></div>
</div>
</div>
<div id="element-container">
<div class="element">
<div class="button">Button</div>
<div class="green-square"></div>
</div>
<div class="clear"></div>
</div>
<div class="add-element">Add Element</div>
Then you can amend the Add Element button to append to that container:
$('div.add-element').click(function (event) {
$('div.element-holder').children('div').clone().appendTo('#element-container');
});
Finally you can add the delegated event handler to the new #element-container. Note that I also shortened the logic using toggle() and siblings():
$('#element-container').on('click', 'div.button', function (event) {
$(this).siblings('.green-square').toggle()
});
Example fiddle
In order to copy event handlers you should send true in the clone method:
$('div.add-element').click(function(event) {
$('div.element-holder').children('div').clone(true).insertAfter($('div.element-holder'));});
I have a block of code that is attached to a jQuery click event. Here's the element:
<!-- Profiles -->
<div class="profiles">
<h1>Profiles</h1>
<div class="profile">
<div class="name">
<input type="text" maxlength="14" value="Default" />
<span class="rename">q</span>
</div>
<div class="controls">
<span class="edit">EDIT</span>
<span class="duplicate">COPY</span>
<span class="delete default">J</span>
<div class="alert-box">
<p>Are you sure you want to delete this profile?</p>
<div>Y</div>
<div>N</div>
</div>
</div>
<div class="saved">
<span class="cancel-button">Cancel</span><span class="save-button">Save</span>
</div>
</div>
</div>
When the item is selected, it becomes available for editing. Here's the event listener:
$('.rename').click(function () {
$('.selected .rename').fadeIn(80);
$(this).fadeOut(80);
$(this).parent().addClass('selected');
});
There's another event that listens for a click anywhere else on the page to deselect the item being edited:
$(document).click(function () {
$(".selected .rename").fadeIn(80);
$('.name').removeClass('selected');
});
When it is clicked on, it should be selected to allow for editing. When I move the code from the profile into a knockout template, it doesn't listen to the click event anymore. When I inspect the Event Listeners in Chrome's tools, the listener is nowhere to be found. Here is what my template looks like:
<div class="profiles">
<h1>Profiles</h1>
<div data-bind="template: { name: 'profilestempl', foreach: $root.profiles }"></div>
</div>
<script type="text/html" id="profilestempl">
<div class="profile">
<div class="name">
<input type="text" maxlength="14" data-bind="value: name" />
<span class="rename">q</span>
</div>
<div class="controls">
<span class="edit">EDIT</span>
<span class="duplicate">COPY</span>
<span class="delete">J</span>
<div class="alert-box">
<p>Are you sure you want to delete this profile?</p>
<div>N</div><div>Y</div>
</div>
</div>
<div class="saved">
<span class="cancel-button">Cancel</span><span class="save-button">Save</span>
</div>
</div>
</script>
Can someone explain to me why the event listener no longer works on the dynamically added elements? I would also like help in solving this problem. Thanks!
You have to add click event listener on the outer element which is always visible (since it doesn't work on hidden elements). And then add other selector for template code (which is hidden)
Sample code would be:
function addClickEventToCloseButton(){
$("#outerAlwaysVisible").on('click','#templateHiddenInitially',function(){
alert('works')
});
}
If you want the handler to work on elements that will be created in the future you should use on : http://api.jquery.com/on/