I am trying to pull all images from a folder on a page. Then I have added html class to the '.append' function against an element of jquery inside ajax. Now I want to use the class outside ajax in another function. But it seems the class was local and hence not defined outside ajax. Can you please tell me how to solve this? My code -
/* html code */
<body>
<div id="imageWrapper">
<div id="spanImage"></div>
</div>
<script>
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("#spanImage").append( "<img src='"+ folder + val +"' class='imageThumbnails'>");
}
});
}
});
/* I have added class = 'imageThumbnails' dynamically to each image appended. Now I would like to use the class to work on individual image to make them pop up
*/
$(".imageThumbnails").click(function() {...}
</script>
</body>
This is not working as 'imageThumbnails' is not recognized by the system as a valid class. Can you please help?
you can use below code to bind event
$(document).on("click",".imageThumbnails",function() {...});
this call dynamic binding.
Delegate it. Attach the listener to its parent and let the event bubbles.
$("body").on('click', '.imageThumbnails', function() {...}
See Its working..
You are not closing your clicking function .`
$(document).ready(function () {
$(".imageThumbnails").click(function() {...})
})
`
(function () {
$('body').append('<img class="imageThumbnails" src="some.png" alt="submit" >')
})()
$(document).ready(function () {
$('.imageThumbnails').click(function () {
console.log('work');
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I have a issue in my js file.
This is my Js Code.
<script type="text/javascript">
$(document).ready(function()
{
$(".abc").click(function()
{
$(this).addClass('testingClass');
});
$(".testingClass").click(function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
});
</script>
My HTML :
<button class="abc">Demo</button>
When i load this page in Browser, The addClass function is successfully executing and adding new class named "testingClass".
But When Try to click again t that button (meens : class="testingClass") the alert function does not working. What is the error.
Is JS is not supporting frequent execution of an element ?
Anybody Please help me.
Steps..
One Button has class named abc
When click on it an ajax function will storing current time in database.(ajax function not in stack-code).
after successful ajax response the button class changed to testingClass.
now the class name of the button is testingClass
After some time Click on the Button again (class named:testingClass), i want to call a ajax function with current time of click and store the values in database.
Then the Button class name will changed to old ( abc).
You need to event delegation for dynamic added element
$(document).on("click",".testingClass",function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
Event delegation
Update
For the changed question, you are looking for something like this.
Here is a demo.
$('body').on('click', '.abc', function () {
// event attached to .abc
// updateTime is a method that takes context (this), current timestamp and a function
// we need to send the context so that we have access to the current
element inside the below function which is executed outside the scope
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('testingClass').removeClass('abc');
$('#log').append('Time: ' + data + 'from abc <br/>');
});
}).on('click', '.testingClass', function () {
// event attached to .abc
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('abc').removeClass('testingClass');
$('#log').append('Time: ' + data + ' from testingclass <br/>');
});
});
function updateTime(currentTime, successCallback) {
$.ajax({
context: this, // the context sent from the above methods is used here
url: '/echo/html/',
data: {
html: currentTime
},
method: 'post',
success: successCallback
});
}
Using .one() will help you attach event only once upon multiple clicks.
This handler is executed at most once per element per event type.
I think this is what you are looking for. Adding a handler after the class is added.
$(".abc").click(function(){
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
$(document).ready(function() {
$(".abc").click(function() {
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>
What I want to do is I have a code like below :
$(document).ready(
function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
}
)
And now I want to add this code to add and get work with other code. I need to add this code after this one:
function () {
/* If there are forms, make all the submit buttons in the page appear
disabled and prevent them to be submitted again to avoid accidental
double clicking. See Issue 980. */
jQuery(function() {
/* Delegate the function to document so it's likely to be the last event
in the queue because of event bubbling. */
jQuery(document).delegate("form", "submit", function (e) {
var form = jQuery(this);
if (form.hasClass("form_disabled")) {
e.preventDefault();
return false;
}
else {
form
.addClass("form_disabled")
.find(":submit")
.addClass("disabled");
}
// Reactivate the forms and their buttons after 3 secs as a fallback.
setTimeout(function () {
form
.removeClass("form_disabled")
.find(":submit")
.removeClass("disabled");
}, 3000);
});
});
}
How can I get this done. Please help me out to solve this problem.
You can create document.ready() anywhere in script. It is not necessary all of your code should be in ready function.
You can create instance variable for function and call it where you need:
$(document).ready(
var myFunc = function(){
var currentPage = window.location.pathname;
//other code
}
...
//and invoke it where you need
myFunc();
)
First, name the long function in your code section, for example, launchFormControls(). And then define the function outside of the document ready event. A good practice would be to do so and keep the ready event body clean.
For example:
function launchFormControls() {
//function code
}
Or, in other syntax:
var launchFormControls = function() {
//function code
}
Second, call your function from within the document ready event. Your function will be defined and able to call once the document is loaded. This code can be placed at the top or bottom of your javascript section or file.
For example:
$(document).ready(function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage+'"]').closest('li').addClass('active');
launchFormControls();
});
I have a small problem that should be very easy to overcome. For some reason I cant work this out. So the problem is I cannot get a button to link to some jquery. My set-up is as follows (showing the relevant code):
Default.aspx
jQuery:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
});
}
jQuery(document).ready(function () {
getContent();
});
HTML:
<div id="content"></div>
ContentService.vb
<WebMethod()> _
Public Function GetContent(number As Integer) As String
Dim sb = New StringBuilder
sb.AppendLine("<table>")
sb.AppendLine("<tr>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Number</td>")
sb.AppendLine("</tr>")
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & number & "</td>")
sb.AppendLine("<td><a href='#' id='test' class='fg-button ui-state-default ui-corner-all'><img src='" & Context.Request.ApplicationPath & "/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
sb.AppendLine("</table>")
Return sb.ToString
End Function
So that's the basics of what I have everything works but I'm not sure how to get the a button (id='test') to get linked to some jQuery. I want it to be pressed and bring up a popup.
I have tried to put the jQuery on default.aspx but this doesn't seem to work unless the button is place in the HTML on that page.
$('#test').unbind('click').click(function () {
alert('Working');
});
I'm sure this is easy to do, but I have been trying for a while and cannot seem to get it to work.
Is the problem that you're trying to bind to the element that ISN'T in existance yet?
are you calling the $('#test').unbind('click').click(function () {
alert('Working');
}); BEFORE the service has returned?
$('#test').on('click', function () {
alert('Working');
});
This will bind the event to the '#test' element once it has been inserted in to the DOM.
As you load the content via ajax, you have to bind to $('#content'). Like this:
$(function () {
$('#content').on('click', '#test', function () {
e.preventDefault(); // if a default action is not needed needed
alert('Working');
});
});
I guess this is about not preventing the default behaviour of the A href tag. Now it will probably link to '#' instead of firing the onclick event.
$('#test').on('click', function (e) {
alert('Working');
e.preventDefault();
});
You could try to wrap this in a document ready, or eventually use the .on binder from jQuery, since it's dynamic content.
Solved
It was a very small thing that caused this. The code to fix this problem is as follows:
$('#test').unbind('click').click(test);
This needed to go inside the function with the json so:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
$('#test').unbind('click').click(test);
});
}
Thank you to everyone that has tried to help me.
I have a javascript function that i have named refreshProjects(), what it does is filter a dropdownlist depending on what was selected in a previous dropdownlist. But i need to also filter my list direcktly after the page has finishd loading.
I have tried using the code window.onload = refreshProjects(id) with no sucsses, but onload workes when i use window.onload = alert('This page has finished loading!'), so i know that part off the script works. So how do i call a javascript function on load, i thought that it would be simple but evrything i tried have failed.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
window.onload = refreshProjects(id); <-- Problem
$("#ddCustomers").change(function () {
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#ddProjects");
$.get('#Url.Action("FilterProjects","TimeEntry")', { customerId: id },
function (result) {
// clear the dropdown
projects.empty();
//Add a deafult "null" value
$("#ddProjects").get(0).options[0] = new Option("[ - No project - ]", "-1");
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}</script>
}
This is for MVC 4.5.
Try changing window.onload = refreshProjects(id); to:
window.onload = function() { refreshProjects($("#ddCustomers").val()); };
Onload expects a callback function. You were directly executing refreshProjects() and setting the return value as the onload.
But since you seem to be using jQUery, you could do the following:
$(function() {
refreshProjects($("#ddCustomers").val());
});
This will execute refreshProjects when the document is ready (which actually is before window load).
You can also try to use the following:
$(document).ready(function () {
refreshProjects(id);
});
This should work aswell if you are using jQuery.
I've attached an onlick event to a function. I want to reference the element being clicked from inside the function so I can change its inner HTML, but why is it not working? Is there any other way to reference the clicked element?
HTML
<div class="save_button" onclick="toggle_save_star(<?php echo $listing->listing_id ?>,'<?php echo base_url()?>')">
<?php if($listing->saved_element_id):?>
<img src="<?php echo site_url('images/core/icons/basic2/star1_16.png')?>" />
<?php else:?>
<img src="<?php echo site_url('images/core/icons/basic2/star1_16_gray.png')?>" />
<?php endif; ?>
</div>
Javascript Function
function toggle_save_star(element_id, site_url) {
var url = site_url+"AJAX/ajax_default/modify_saved";
var button = $(this);
$.post(url,{action: 'toggle', element_id: element_id, type: 'listing' }, function(data) {
if(data == 'saved') {
$(button).html('<img src="'+site_url+'images/core/icons/basic2/star1_16.png" />');
}
else{
$(button).html('<img src="'+site_url+'images/core/icons/basic2/star1_16_gray.png" />');
}
});
}
I think in this case "this" don't reference to the div. You should try:
$('.save_button').click(function(){
$(this)...
});
Try $("#"+element_id) instead. $(this) isn't working because you're not running this function as a method on an object.
Improving on the other answers, try this:
$(".save_button").click(function(){
toggle_save_star(element_id, site_url, $(this));
});
and in your function, the third new argument (called "target", let's say) could be used like this:
var button = target;
then use button like button.html(...);
The main problem here is that when you assign a string to onclick in your markup as in:
<div class="save_button" onclick="toggle_save_star..."
then, the code in the quotes gets evaluated by eval() and the this pointer will be set to point to the window object, not to the object that generated the click. If you want this set appropriately, then you can't assign the onclick handler in the markup, you would need to do it with JS as in:
$(".save_button").click();
or some other way in code.
In addition, there's a coding error in your toggle_save_star function.
Your button variable is already a jQuery object so you don't need to try to make it into another one with $(button). If you were going to use that function, you would have to change it to this:
function toggle_save_star(element_id, site_url) {
var url = site_url+"AJAX/ajax_default/modify_saved";
var button = $(this);
$.post(url,{action: 'toggle', element_id: element_id, type: 'listing' }, function(data) {
if(data == 'saved') {
button.html('<img src="'+site_url+'images/core/icons/basic2/star1_16.png" />');
}
else{
button.html('<img src="'+site_url+'images/core/icons/basic2/star1_16_gray.png" />');
}
});
}
You would be better off removing the onclick from your div and going with something like the following:
http://jsfiddle.net/cpeele00/epD3v/
This allows you access the clickable item, in this case 'save_button'.
Then, at the bottom of your page (before you reach the closing body tag, insert your script there).
<script>
$(document).ready(function(){
//CALL THE FUNCTION HERE
//DEFINE THE FUNCTION HERE (see the jsFiddle link above)
});
</script>
</body>