jQuery code does not fire on modal forms - javascript

I have a simple link that will fire an ajax call and change a status, and I want that new status reflected (instantly) on the modal form.
Problem is: when I click the link that is on the modal form (below), nothing happens.
<a title="Autoplay" data-placement="top" data-toggle="tooltip" class="glyphicon glyphicon-stop" id="autoplayStatus" href="#"></a>
In $(document).ready(), I have this:
$("#autoplayStatus").click(function(event){
alert('test');
})
Is there something I should do to ensure that jQuery can select and bind to objects on a modal form?

To ensure that jQuery binds to buttons (or other stuff) in modals created by Bootstrap, you should write your event handler like this:
$(document).ready(function() {
$('.container').on('click', '#autoplayStatus', function() {
alert('Ohai!');
});
});
and then, in my example, wrap the anchor tag in a container:
<div class="container">
<a title="Autoplay" data-placement="top" data-toggle="tooltip" class="glyphicon glyphicon-stop" id="autoplayStatus" href="#"></a>
</div>
On a sidenote, it's better practice to use <button> instead of <a> when creating, well, a button. =)

Related

How to click on a link inside the data-content of a pop-over?

I have added links into popover data-content. How can I perform a click() action on the links I have placed inside the data-content of popover-->(Bootstrap)
I have provided html anchor tags inside the data-content="" attribute of popover button.
Below is a link which upon clicking will show the popover content. The data content inside the popover has one upload and one download link.
Now I want to perform click action on the upload and download link. How can I do that?
<html>
<body>
<a href="#"
data-toggle="popover-upload"
data-trigger="focus"
data-placement="bottom"
title=""
data-content="<div class='link-Updown'>
<a href='' class='upload' title='Upload the Zip file here'
style=&quot margin: 7px;margin-bottom: 7px;display:block;&quot>Upload</a>
<a href='' title='Download'
style=&quot margin: 7px;margin-bottom: 7px;display:block;&quot>Download</a></div>"
style="font-family: calibri; font-size: 15px;color: darkslategrey;font-weight: bolder" ><i>Upload/Download</i>
</a>
<script>
$(document).ready(function(){
$('[data-toggle="popover-upload"]').popover({html:true})
.on("click",function(){});
})
</script>
</body>
</html>
The problem is that the popover content is inserted dynamically. This means that on init the html is not present in the DOM so no click event can be attached yet.
To solve this you can delegate the event by making a parent element listen to the event:
<a href="#" data-toggle="popover-upload" data-content="
<div class='link-Updown'>
<a href='#'>Upload</a>
<a href='#'>Download</a>
</div>">
Upload/Download
</a>
<script>
$(document).ready(function() {
$('[data-toggle="popover-upload"]').popover({ html: true });
// delegate click event from the document
$(document).on("click", ".link-Updown a", function(event) {
event.preventDefault();
console.log("download or upload clicked")
})
});
</script>
Right now you're listening to clicks on the container element instead of the anchor tags within the popover content.
You could do something like this:
$('[data-toggle="popover-upload"]').popover({
html:true
}).parent().on('click', '.link-Updown a', function(e) {
e.preventDefault();
// do your thing
});
You could distinguish between clicks on Upload or Download by giving them a data attribute data-action which you can read with $(this).data('action').
See this working fiddle.

Turning a div and its children into a modal/popup?

I am trying to have the div and its children show in modal/popup while still remaining in their original DOM positions. I am unable to move the div, or its contents, around in the DOM because of some javascript that requires extensive tree traversal when a checkbox is clicked inside of the parent div. We are using bootstrap modals in the project, so a solution that allows me to use a modal would be ideal.
*I know I can achieve this with custom CSS, but I would like to know if there is a cleaner way (Example: $('div').modal('show')), rather than me faking a modal/popup
<!--datagrid-fields is what I am trying it make into a modal/popup-->
<!--getSelect() just returns an HTML checkbox list-->
<li id="gridCheckboxesEntryInfo" class="threeColumns">
<input type="checkbox" onClick="selectAllFields(this)"> Select All<br>
<a class="btn btn-primary reorderFields" data-toggle="modal" data-target="#reorderModal">Reorder Fields</a>
<a class="btn btn-success selectFields">Select Fields</a>
<div style="display:inline-block;margin-left: 5%;"><h3 style="display:inline-block;font-size: 18px">Scroll Down to View Fields</h3><div class="arrow bounce"><a class="arrow bounce"><i class="fa fa-arrow-down fa-2x"></i></a></div></div>
<div id="datagrid-fields">
<?=getSelect($fieldsbysetwithwidget, $fieldsindb, 'checkboxes');?>
</div>
</li>
You can clone a div before making a popup of it.
$('#datagrid-fields').clone().modal('show')
Note, you need to clean up some attributes like id if it is used somewhere else. In addition you have to remove modal div on close:
$cloned.on('hidden.bs.modal', function () { $cloned.remove() });
You probably need to wrap cloned contents with modal wrapping div like
$cloned.wrap('<div class="modal ..."></div>');
So the final version is
var $cloned = $('#datagrid-fields').clone();
$cloned.wrap('<div class="modal ..."></div>');
var $modal = $cloned.parent();
$modal.on('hidden.bs.modal', function () { $modal.remove() });
$modal.modal('show');

Using Bootstrap 3 popover and loading external JSON

I am loading external JSON and would like to use Bootstrap popvers.
Their sample code is like:
HTML:
<button data-toggle="popover" title="Dismissible popover" data-content="And here's some amazing content. It's very engaging. Right?">jonathan</button>
and presumably:
$('[data-toggle="popover"]').popover();
However, it would seem since this is from loaded JSON, I would have to do something like:
$('body').on('click', '[data-toggle="popover"]', function(){
// would I call somehtig like
$(this).popover();
});
The only way I can get this to work is like:
$(window).load(function(){
$('body').on('click','[data-toggle="popover"]', function(){
//alert('here i am');
$(this).popover();
});
});
and it only works on the second click. How would I implement this? I'd rather have it just be a hover rather than a click too
The reason for the popover to come on the second click is the way you're initializing your popover.
$(window).load(function(){
$('body').on('click','[data-toggle="popover"]', function(){
//alert('here i am');
$(this).popover();
});
});
Here you're initializing without any options so the default trigger for your popover will be click event and you're doing this initialization when you click on the body. That's the reason you need 2 clicks to show the popover.
To avoid this, you need to register the popover on your button on page load and define the trigger of your interest (click or hover) using data-trigger attribute in HTML.
HTML
<a id="example" tabindex="0" class="btn btn-lg btn-danger"
role="button" data-toggle="popover"
data-trigger="hover" title="Dismissible popover"
data-content="And here's some amazing content. It's very
engaging. Right?">
Dismissible popover
</a>
JS
$(document).ready(function(){
$('#example').popover();
});
You can also define the trigger and other options while initializing the popover like below.
$('#example2').popover({
trigger : 'hover'
});
Here's a Pen to showcase the implementation.

Onclick for dynamically created elements using jquery

Onclick event is just not working for me. When mouse in over some div, I dynamically insert some icons using .html() function, and want to set onclick on that icons but i can't. I also tried setting click listener for the static enclosing div (jquery .on('click', ..) function) or for the whole page but it's no use, as if those icons just swallow the click event... Any ideas?
<div id="rating" class="pull-right rating-box clearfix">
<i class="fa fa-star"></i>
<i class="fa fa-star-o"></i>
<i class="fa fa-star-o"></i>
</div>
Here is html
I have tried a lot of way of doing, but here is the latest thing i tried
$(document).ready(function()
{
//some code
$('#rating').html(/* some combination of <i class="fa fa-star"></i>'s */);
$('#rating').on('click', 'i', function() { });
});
Use the .append() method instead:
$('#rating').empty();
$('#rating').append(/* some combination of <i class="fa fa-star"></i>'s */);
$('#rating').on('click', 'i', function() { });
jsFiddle
See jquery .html() vs .append() for more information.

onClick does not function inside a dynamically generated div

I have a jquery code which generate a div dynamically
the problem is that the onclick function for the a tag does not calls the required function
Here is the code
$("#new").append('
<ul class="#...#">
<li>
<a href="./d.html?n1='+item[0]+'&n2='+item[2]+'&n3='+item[3]+'">
<input type="hidden" value='+item[0]+'>
<img style="height: 64px; width: 64px;" class="#...#"
src="image.png" width="40" height="40" />
<span class="#...#">
<b>'+item[0]+'</b>
'+item[1]+'......
</span>
</a>
<br />
<div>
<a onClick="insert();" href="#">
<i class="icon1"></i>
</a>
<a href="2.php?q='+q+'&n='+item[0]+'" id="icon2" name="icon2">
<i class="icon2"></i>
</a>
</div>
</li>
</ul>
');
I am using the above code as an ajax success function
the a tag is not calling the insert() function
I searched for the error but could not find the
What am doing it wrong?
Thsnks in advance
Add a custom class, such as "catchClick" to the element that you need to catch the click event of.
var linkToAdd = '<a class="catchClick" href="#">My link</a>';
var $linkToAdd = $(linkToAdd);
$('#new').append($linkToAdd);
Then the following code will setup handlers for clicks on that element.
It works because the click event is bubbled up the dom hierarchy to the document element. So you can attach a listener to the document element instead.
$(document).on('click', '.catchClick', function(e) {
// do your stuff here
// you probably need to get a jquery reference to the element that was clicked:
var $this = $(this);
// you probably want to stop the event's default actions so we'll add this:
e.stopPropagation();
e.preventDefault();
});
When you work with dynamic content I suggest you use DOM event delegation. The ideea is to add the listener on a parent of your dynamically added content
This explains how to do it and how it works
http://davidwalsh.name/event-delegate
Use JavaScript event delegation to separate concerns:
$(function() {
$(document.body).on('click', 'ul.someClass div a', function() {
// insert() method logic goes here
});
});
Second argument specifies the event target. This event is bind to the document's body so it's always present. Target DOM objects can be generated per AJAX at some point later or removed from the document. The actual target check happens when a user actually clicks something.
Also adding a class attribute to <div> or <a> in your code might help with readability. E.g.:
<div class="buttons">
<a class="btn-insert" onClick="insert();" href="#">
<i class="icon1"></i>
</a>
<a href="2.php?q='+q+'&n='+item[0]+'" id="icon2" name="icon2">
<i class="icon2"></i>
</a>
</div>
Target attribute for jQuery on() method could then be simplified to just '.btn-insert'
Set the click event handler AFTER having appended new clickable items to the document, and subsequently after each time you append new clickable items to the document.

Categories