How to load a specific div/class in a file using ajax? - javascript

I have a file called main.html that contains several div's each with 2 classes:
1st is their specific class 2nd is a class called menu-item which I use to determine if an event will triggered when clicked.
The file contains this:
<div id="load-here">
</div>
<div class="item-1 menu-item">
click this
</div>
I also have a gallery.html file which I want to be loaded into the main.html file in the #load-here div, and let's say it contains this:
<div class="menu-item>
<!-- some image here -->
<img href="img/1.jpg />
</div>
The script I have is this:
$(document).ready(function() {
$( "div" ).click(function() {
if ( $( this ).hasClass( "menu-item" ) ) {
$("#load-here").load("gallery.html" + this.class);
}
});
});
The problem: It's not working. I've tried various changes. Somehow it's not loading into the #load-here div

Take a look at this: http://api.jquery.com/load/
$( "#b" ).load( "article.html #target" );

There seem to several issues:
By this: $( "div" ).click(function() ... you are registering the click on all divs available. This might cause strange behaviour. Better use: $("div.menu-item").click( ...
Make sure you understand the context and the event target in your callback function. Sometimes this is cheating you, as the context of the call may be different. Things are more clear if you handle the event as explicit parameter and check the event target.
I guess you would like to give a parameter for your gallery.html, but as #charlietfl mentions, there is no .class. But, in the DOM there is a .className. Better try to use the jQuery $().attr('class'). Also, the parameter needs a separator: gallery.html?parameter
To sum it up, here my suggestion:
$("div.menu-item").click( function(event) {
var jqTarget = $(event.target).closest('.menu-item');
if ( jqTarget.hasClass( "menu-item" ) ) {
$("#load-here").load("gallery.html" + "?" + this.class);
}
});
closest() will attempt to find the closest matching element, in case the click target was not on the div itself, but rather a child img or else. So, the condition in the suggestion should be used to find out about more specific about which menu item was clicked: if ( jqTarget.hasClass( "that-specific-item" ) ...

Related

Disable javascript in a element

I have an element with a a script for a mouseover to show an image. I can't change the HTML, so is it possible to disable the javascript in the link, but still keep the link for the href intact? I cant use the id of the a element since it isn't unique.
HTML:
<div class="container">
<a id="a211094" onmouseout="etim();" onmouseover="stim('/imgs/7c24b548-4f4c-418e-ad4f-53c73cf52ace/250/250',event,this.id);" href="/products/Computers/Desktops/Acer/Acer-Aspire-TC-705W-Towermodel-1-x-Core-i3-41?prodid=211094"><img src="" alt="">
</a>
</div>
if you want to make all ancher tag or you can give class for those anchor tags on which you want to perform this and instead of $( "a" ) write $( ".myClass" )
$( "a" ).each(function( index ) {
$( this ).removeAttr("onmouseout");
$( this ).removeAttr("onmouseover");
});
use can use attr("disabled", "disable"); to disable it
Overwriting the JavaScript:
document.getElementById("a211094").onmouseover = null
document.getElementById("a211094").onmouseout = null
document.getElementById("a211094").removeAttribute("onmouseout");
document.getElementById("a211094").removeAttribute("onmouseover");
If you can consistently access and control the containing element you could try a slightly left-field approach using an onmouseover event on the container.
There's a function called setCapture() which you can call during a mouse event to "capture" all mouse events of that kind for the element it's called against, until a mouseup event or releaseCapture() is called. So you could do something like the following:
jQuery(document).ready(function() {
$container = jQuery("#<yourcontainerid>");
$container.on("mouseover", function(e) {
if (e.target.setCapture) e.target.setCapture(true);
});
$container.on("mouseout", function() {
document.releaseCapture();
});
});
The (true) argument is important (I think, without testing) as it prevents any descendent events firing, which is what you want here.
The mouseout function will then release the capture when it leaves the area of the container.
Will this work? can't say for sure, I haven't tested it in your exact case, but in theory it should!
UPDATE: you can use ".container" rather than "#yourcontainerid" in the JQuery if you so wish to enable this for everything of class container.

Trigger Event on Ajax generated Element

I can't use any Event (eg. onlick) on any ajax generated element. I read about jQuery's ".on" function, but I need to use something like <div id="myId_1234" onlick="doStuff()">.
The Id of the Element is random, so I can't use
`$('.some-parent-class').on('click', '.element', function() {// DO STUFF!});`
I hope someone can help me! Thanks.
You could attach the event handler to your element in the AJAX response before adding it to the DOM by using
$(responseHtml).find('some selector').on('click', handler);
There is most likely one or more attribute selectors that will work for you.
Ex: id begins with selector
$(responseHtml).find('div[id^=myId]').on('click', handler);
If you cannot differentiate which element in the response you need with a css selector you will have to modify the server script generating the HTML with a unique id or class that matches a pattern you can look for.
EDIT
You CAN use a css class to identify each element. use:
$('.myCloseButtonClass').on('click', function(){ $(this).parent.hide(); });
The key here is the this object. It will reference the specific element that was clicked thereby allowing you to close only the chat window that contains the clicked close button.
JSFiddle using AJAX echo
$('.some-parent-class').on('click', 'this put your id input', function() {// DO STUFF!});
proib with this......
You could do something like:
<div class="myBoxes">
<div id="oneBox" onclick="myFunc(this.parentNode);">
<p>Some content..</p>
</div>
</div>
function myFunc(){
// Code goes here
alert('function fired!');
}
I am simulating the Ajax Generated part by dynamically generating a clickable DIV element.
HTML:
<div id="container">
</div>
JS:
$("#container").append(
$('<div>').attr('id', 'randomId').html('New element')
);
$("#randomId").click( function(){
alert('Clicked!!!');
});
EDIT: Same example using class instead of Id:
$("#container").append(
$('<div>').attr('id', 'randomId').addClass('parent-class').html('New element')
);
$(".parent-class").click( function(){
var clickedElementId = $(this).attr("id");
alert('Element with ID ' + elementId + ' Clicked!!!');
});
Working fiddle

get id of first child of class and then trigger onclick event of that

I am dynamicaly creating html as below,
<div id="disc_cat">
<ul class="viewCatList">
<img id="prod1" src="../products/ `Image_url`" class="slide_contain" onclick="getCanvas(1,1,1,1,1,1,1,2,' `Image_url`')">
<img id="prod3" src="../products/ `Image_url`" class="slide_contain" onclick="getCanvas(1,1,1,1,1,1,1,2,' `Image_url`')">
</ul>
</div>
I am trying to trigger click event of first image , but i dont know the id.
I tried ,
$( "ul.viewCatList" ).find("img:first").attr("id"));
and many things , what is the correct way to get id of first child in viewCatList
Why do you want the id, once you have the jQuery wrapper for the element just call the click() on that
$( "ul.viewCatList" ).find("img:first").click()
The below code will get you the first id of image and then you can use along with # for click event..Comment here for further queries
$(document).ready(function(){
var x=$( "ul.viewCatList" ).find("img:first").attr("id");
alert(x);
$("#"+x).click(function(){
// do your stuff here..
});
});
$( "ul.viewCatList" ).find("img:first").attr("id"));
is working fine. It gives your the ID "prod1" of first image element.
But as you know, that click event is bind on jquery element object. So you can directly call click event on $( "ul.viewCatList" ).find("img:first") like below.
$( "ul.viewCatList" ).find("img:first").click(function(){
console.log("Here is your image1")
})

JQueryUI how to 'self' close a dialog

I'm working on a web app that uses jQueryUI and creates a ton of dialogs. The dialogs are all different, and the button to close the dialog can end up embedded several div's into the dialog.
I'd like a function that always closes the containing dialog.
Take for example the following html:
<div id="demoDialog">
<div>
<div id='demoDialogSubmit'>
<input type='submit' onClick='selfCloseDialog();' value='Ok' style='margin-top:10px' />
</div>
<div>
<div>
Somewhere in my js code I initialized this as a dialog:
$( "#demoDialog" ).dialog( params );
Now for the on-click I have a few not so great choices. I could insist on the close button knowing the id of the dialog. E.g. do something like:
onclick="$( '#demoDialog' ).dialog( 'close' );"
But I'd rather have generic code instead of always having to carry around the id of the dialog so I can send it to a widget that may close it.
Or I can remember how many layers down I am:
function selfCloseDialog() { $(this).parent().dialog( 'close' ); }
But really I want selfCloseDialog() to just hunt up the layers of elements looking for the dialog object to close. How do I do this?
#Update:
So i got it working. Thanks everyone for their suggestions the problem actually had two issues.
First one problem was here:
<input type='submit' onClick='selfCloseDialog();' value='Ok'/>
It should be:
<input type='submit' onClick='selfCloseDialog(this);' value='Ok'/>
The button element is not passed in as the "this" argument to the function. Which seems obvious now.
And the following direct method JAAulde below works and seems the cleanest:
function selfCloseDialog( caller ) {
$(caller).closest( ".ui-dialog-content" ).dialog('close');
}
There were several answers involving closest and a selector- but I don't see any reason to use anything except the plain class selector he suggests.
When making your dialog, include a close button:
var params = {
//whatever you already had in there
buttons: {
// In the buttons object, the "key" will be the button text, the function
// will be executed on click of the button in scope of the dialoged element
Close: function () {
$(this).dialog('close');
}
}
};
$( "#demoDialog" ).dialog( params );
And from code running in scope of ANY descendant element of the dialoged element, run:
$(this).closest('.ui-dialog-content').dialog('close');
Not sure if I'm exactly understanding what you're asking, but it seems the easiest way would be to add a standard class to all your dialogs, and then have code like:
$(this).closest('.dialog-class').dialog('close');
closest() is defined here:
http://api.jquery.com/closest/
*updated to reflect the ajax part of the dialog. *updated to reflect comments
<div id="soemthing.random.ui.dialog.makes">
.... your content....
<a class='custom-close' href="#Close">Custom Close</a>
....
</div>
$(function(){
$("your selector").dialog();
var selector = ":ui-dialog";
//developers choice. ".ui-dialog-content" is faster, ":ui-dialog" is guaranteed
$(selector ).on({
"click":function(event){
event.preventDefault();
$(this).closest(selector).dialog("close");
}
},"a.custom-close",null);
})
I'd suggest using a class instead of writing inline function calls, but that's up to you.
Here's my hackish solution with event delegation where clicking an element with the selfclose class will close the ancestor dialog:
$(document).on('click', '.selfclose', function() {
$(this).parents().each(function() {
try {
$(this).dialog('close');
} catch(e) {}
});
});
Fiddle
But as DefyGravity mentioned, using the :ui-dialog selector is a much cleaner solution:
$(document).on('click', '.selfclose', function() {
$(this).closest(":ui-dialog").dialog("close");
});
Fiddle
check this:
http://jsfiddle.net/Wqh4Y/3/
function closeParentDialog(closeButton)
{
closeButton.parents('.ui-dialog').eq(0).find('a.ui-dialog-titlebar-close').eq(0).click();
}
$(function() {
$( "#dialog" ).dialog();
});​
you can use it like this:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.
<span> <a class="close-dialog" onclick="closeParentDialog($(this))">selfclose</a> </span>
</p>
</div>

Referencing a div (by id) that has been append()ed into the content

I have a div I'm creating dynamically, with a unique id. I append() that to an area on the page.
Later, I try to reference that via $( '#id_here' ), but it returns nothing. Inspector in safari/chrome shows the existence and proper id of the element.
<script>
$( '#box' ).append( '<div><input id="id123" /></div>' );
//Later on in time...
function doingStuff(){
alert( $( '#id123' ) );//undefined
}
</script>
<div id="box">
</div>
Make sure that you append the object not before the DOM is ready, otherwise you will probably not able to access #box yet.
$( document ).ready( function()
{
$( '#box' ).append( '<div><input id="id123" /></div>' );
} );
You're doing it right, it's just your alert statement that might be a bit off. Currently, your passing the jquery result to the alert(), which just reports "[object Objerct]" (in Chrome anyway. It'll differ for each browser).
Try:
alert($("#id123").val());
That would alert the value in the text box.
or
alert($("#id123")[0].id);
That would alert the id of the input (id123).
Perhaps you have an error elsewhere in your code? What you've posted works fine.
UPDATE
As others have pointed out (and I missed), your script is running before the div is appended to the document, hence the "undefined". Preventing your script from running by wrapping everything in:
$(document).ready(function()
{
// Script here
});
is the way to go.
Tell jQuery to wait for the document to be ready before appending the div. This way, the document (and #box) is loaded and ready to be used before jQuery starts with its work. You do this by doing:
$(document).ready(function() {
$( '#box' ).append( '<div><input id="id123" /></div>' );
});
You can keep the rest of the code as it is
Comments on my poorly hacked together and un-tested example were all fair.
Turns out my problem was a special character in my div id.
It's been a long day.
The best way I've used to get arround that type of problems is to use .live() from Jquery, which attaches a handler to the desired event to be used on existent elements or elements to be created later on (like .append())...
Ex.:
$('#box').append('<div><input id="id123" /></div>');
$('#id123').live('click', function() {
// Your Desired Code for that ID
});
Read more about this at: Jquery .live()

Categories

Resources