I am using jquery to implement some functionality that is repeated multiple place in the same jsp. I want to re-use the same jquery code again. Can anyone let me know how can I achieve that? Hope the below code snippet explain what I really want to achieve.
<div id="1" class="a">
//implement the some functionality to all the
elements that below to this class and id="1"
</div>
<div id="2" class="a">
//implement the similar functionality that is happening
int above div to all the elements that below to this class and id="2"
</div>
<div id="3" class="a">
//implement the similar functionality that is happening
int above div to all the elements that below to this class and id="2"
</div>
<script type="text/javascript">
//Re-usable code goes here that applies for class type 2 and tracks id 1,2,3 differently.
</script>
Edit
I want to use datatable at multiple places in the same html page and at each instance of the datatable used, I want to do similar customization using Jquery.
https://datatables.net/examples/
I think this is what you're after. When any element with id 1,2 or 3 is clicked, then it will execute the same function.
$(document).on('click', '#1, #2, #3', function (e) {
console.log(e.target); // This is the element that was clicked
alert('Clicked')
});
https://jsfiddle.net/cnLvk3o1/1/
If you want to select by class like A.Wolff has mentioned below. You can use this instead.
$(document).on('click', '.a', function (e) {
console.log(e.target); // This is the element that was clicked
alert('Clicked')
});
Related
I am trying to create a to-do list using HTML/CSS, Javascript and JQuery. The problem I have occurs when I try to delete an item off the list. Here is the Javascript.
$(document).ready(function(){
$('#add').click(function(){
if($('#input').val() != '')
$('.container').append('<p class="todo">'+$('#input').val()+'</p><span class="del">×</span><br/>');
});
$(document).on('click','.del',function(){
$(this).click(function(){
$('.todo').hide();
});
});
});
The HTML
<body>
<h1 class="header">To-Do List</h1>
<hr/>
<br/>
<input type="text" id="input"/>
<button id="add">Add</button>
<br/>
<br/>
<div class="container">
</div>
</body>
What the above does is it removes all of the dynamically generated todo [paragraph] elements when a single del element [an x] is clicked. I am asking how to change the code so clicking the del element removes the todo element that it was generated with. I understand I can use ids but I feel that is too cumbersome. Thanks for the help.
You can use .prev() to hide only the immediate previous sibling .todo paragraph of clicked .del:
$('.container').on('click','.del',function(){
$(this).prev().hide();
});
Also take note that you don't need to use .click() event for .del any more since you've already using event delegation to attach the click event to them as well as using closest static parent for delegated event instead of $(document).
Try this jQuery, this also hides the 'x':
$(document).on('click','.del',function(){
$(this).hide();
$(this).prev().hide();
});
This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 9 years ago.
I have a <select class="listenToMe" /> that when changes does something. I also have a separate link that when clicked performs an ajax request and returns more dom elements and inside them it has another <select class="listenToMe" />
I would like my event listener to be applied to this element as well. I am trying to use jQuery's on method but it doesn't appear to be working:
JS
var selectListener = function() { alert('you change me!'};
$('.listenToMe').on("change", selectListener);
$('.addMore').click( function() {
$.post('myWebPage.php', {} , (function(data) {
$(this).before(data);
// data is something like <div><select class="listenToMe" /></div>
}).bind(this));
});
HTML
<div>
<div>
<select class="listenToMe" />
</div>
<div>
<select class="listenToMe" />
</div>
<a class="addMore">Click me</a>
</div>
Any suggestions?
You can try
$(document).on('change', '.listenToMe', function(){
// Your code here
})
Your using on like live. The difference is subtle but important. You attach on to a static element in your markup and then filter the event based on a selector. This way the on event never goes out of scope, e.g. if I have the markup
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
</div>
which when I add my dynamic markup will become:
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
<div class="myDynamicdiv></div>
</div>
To fire an event on the click of my dynamic div that never needs rebinding I would write the following jQuery:
$('#mystaticDiv').on('click', '.myDynamicdiv', function() {/*Do stuff*/});
So I'm binding my on to the #mystaticDiv but filtering on .myDynamicdiv. Now I can add as many .myDynamicdivs as I want and this will work.
I mentioned live. This is deprecated but works in the same way as you were attempting. This attaches an event to the document of the page with a selector base on the selector your attaching live to. So $('.myDynamicdiv').live('click', function() {/*Do stuff*/}); is directly equivalent to $(document).on('click', '.myDynamicdiv', function() {/*Do stuff*/});. the reason I mention this is this is how you were trying to use on.
Your code $('.listenToMe').on("change", selectListener);. Will not work for dynamic content. This code attaches the event to the dynamic content, that doesn't exist yet. So the is never actually bound. Interestingly $('.listenToMe').on("change", selectListener); is exactly what $('.listenToMe').change(selectListener); does under the hood.
I am currently trying to make a wallpaper changer for my page.
At the minute, I would like to put the URL of a wallpaper into a text box when it's respective DIV option in a CSS menu is clicked.
Here is my JQuery
$("div.bg8").click( function() {
var BackgroundURL = 'Styles/hongkongskyline.jpg';
var TheTextBox = document.getElementById('<%=BackgroundsTxt.ClientID%>');
TheTextBox.value= BackgroundURL;
alert('This has worked'); });
.. and my HTML...
<ul><li class="#cssmenu"><a>
<div id="bg8" runat="server">
<table style="height: 16px; width:33%;">
<tr>
<td>
<img src='Styles/hongkongskyline.jpg' width="34px" height="32px" /></td> <td>Hong Kong Skyline </td>
</tr>
</table>
</div>
</a></li></ul>
Unfortunately, nothing seems to be happening when I click the DIV..
Does anybody see any problems which I can't?
Many thanks.
Several problems here.
First, you aren't referring to your div's ID in your jQuery - you're referring to a class called bg8. Try this:
$("#bg8")...
Next, you're mixing in some native-dom stuff into your jQuery. Instead of
document.getElementById('<%=BackgroundsTxt.ClientID%>');
try
$("#<%=BackgroundsTxt.ClientID%>");
and make sure the ID is resolved by looking at the source to your page.
And lastly, to set the value of the textbox:
theTextBox.val(BackgroundURL);
Your whole function could be
$("#bg8").click( function() {
$("#<%=BackgroundsTxt.ClientID%>").val('Styles/hongkongskyline.jpg');
alert('This has worked');
});
My strategy is to test event handlers with simple alerts before moving on to the real logic.
your jQuery states $('div.bg8') , this calls for a div with the class bg8,
you have not set the class, but rather the id of your div as bg8
change this: $('div.bg8') to $('#bg8')
;)
I have a form that I create a checkbox on a click of a button. I am using https://github.com/pixelmatrix/uniform which provides an update function to style dynamically create elements which does not work. I got a work around but my problem is that it also reset the already created elements so they double, triple etc.
They are wrapped in a div with a class of checker. Is there a way to check if the div is around it first before applying my $('.table').find('input:checkbox').uniform(). I have tried different examples but they dont seem to work with my code and my jQuery is still limit.
Thanks
<div class="checker" id="uniform-160">
<span>
<input type="checkbox" name="chbox" id="160" style="opacity: 0;">
</span>
</div>
jQuery:
$(".fg-button").live("click", function(){
$('.table').find('input:checkbox').uniform()
});
Try this:
$('.table input:checkbox').not('div.checker input').uniform()
I'm reading data from a database and adding it to a table to be displayed on a webpage. The table that this data is added to lies inside a panel. To view this table I would have to use this Javascript to expand the panel:
<script type="text/javascript">
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});
</script>
To see where the class names flip and panel come from see below:
<div class="panel">
<table>
...
</table>
</div>
<p class="flip" onmouseover="this.style.color='red';this.style.cursor='hand'" onmouseout="this.style.color='black';this.style.cursor='pointer'"> VIEW TABLE </p>
Now, since I'm reading data from the database iteratively, the number of item in there could be anything.
How do I do this such that each has it's own identity, so that when I click on "VIEW TABLE" then each responds on its own. At the moment when I click on one, all expand and vice-versa, obviously because the share a common class name. I've tried to make sure that the class name be the entry id, but certain things break.
add to the element you want to fire the click event and send a refrence to it for example
the div will have on click event will look like this
<div onclick="MyFunction(this);"> </div>
in the function body recieve the object then reach to the element you want
function MyFunction(sender)
{
$(sender).//now you have the element and could reach to the parent or the child as you want
}
Use .prev() for your layout:
<script type="text/javascript">
$(function() {
$(".flip").live("click", function(){
$(this).prev(".panel").slideToggle("slow");
});
});
</script>
This will select the previous class="panel" to the class="flip" you clicked and slideToggle it. Also, since you may have any number of these handlers that will be the same, I suggest you use .live() like my example above, using 1 event handler instead of n event handlers.
Can you assign a new id for each 'panel' based on something in the db, or just with a sequential number? If so, then you could try this:
<div class="panel" id="panel_1">
<table>
...
</table>
</div>
<p class="flip" onClick="$(".panel_1").slideToggle("slow"); " ... >
<div class="panel" id="panel_2">
</div>
<p class="flip" onClick="$(".panel_2").slideToggle("slow"); " ... >
etc.
Making this assumption: You saying you have a new <div... for each new <p... and that the mouse over (or click) of the <p> should show the cooresponding <div>.
Try using this: for cooresponding instances.
$('.flip').click(function()
{
$('.panel').eq($(this).index()).slideToggle("slow");
});