i have a div for which i set value dynamically during run time, if there is value than i have enable or create a link which will have onclick method where i will call a javascript method.
how to do this in jquery or javascript?
I set value to a div like the following,
document.getElementById('attachmentName').innerHTML=projectInforamtionMap.Cim_AttachmentNames;
this the div :
<tr>
<td align="left"><div id="attachmentName"> </div></td>
</tr>
Kindly help me to find and fix.
Best Regards
You can set a onclick function:
document.getElementById('attachmentName').onclick = function() {};
Assume that your function are previously define like this
function foo(){alert('function call');}
After adding innerHTML
In Javascript
document.getElementById('attachmentName').setAttribute('onclick','foo()');
In Jquery
$("#attachmentName").attr('onclick','foo()');
You have several alternatives
JavaScript:
// var elem = document.getElementById('attachmentName');
elem.onclick = function() {};
elem.setAttribute('onclick','foo()');
elem.addEventListener('onclick', foo, false); // The most appropiate way
jQuery:
// var elem = $('#attachmentName');
elem.click(foo);
elem.on('click', foo);
$('body').on('click', elem, foo);
Between the 3 jQuery alternatives, the last is the best one. The reason is due to the fact that you are attaching an event just the body element. In this case, it does not matter but in other cases, you are probably willing to attach the same event to a collection of elements, not just one.
Therefore, using this approach, the event is attached to the body but works for the elements clicked, instead of attaching the same event to every element, so it's more efficient :)
$('#attachmentName').click(function(){
//do your stuff
})
jquery way:
$("#attachmentName").click(function() {
some_js_method();
});
You can do this without inserting link in the div in following way
document.getElementById("attachmentName").onClick = function () {
alert(1); // To test the click
};
You can achieve it with the help of jQuery as well in the following way.
$("#attachmentName").click(function ()
{
alert(1);
});
for this you have to include jQuery liabray on the page. refer jQuery.com
Still if you forecefully want to include the link in Div then following is the code for it
var link = $("<a>"+ $("#attachmentName").text() +"</a>");
$("#attachmentName").html($(link);
link.click(function () {
alert(1);
});
Hope this would help.
as i was converting a classical asp details page to a one-page ajaxified page, i converted the existing links in the page to get the details loaded in the DIV in the same page. i renamed the href tag to dtlLink and got that data in the jquery load() function.
detail.asp (server.urlencode is added and required here )
<a href=""#"" onclick=""javascript:LoadDetails(this)"" dtllink="detail.asp?x=" & Server.URLEncode(Request("x"))&y=" & Server.URLEncode(Request("y")) > link text </a>
parent.asp (it has some extra code for holdon.js spinner image, button enable/disable, results div show/hide)
Jquery
function LoadDetails(href) {
//get the hyperlink element's attribute and load it to the results div.
var a_href = $(href).attr('dtllink');
console.log(a_href);
$('#divResults').html('');
DisplayHoldOn();
$('#divResults').load(a_href, function (response, status, xhr) {
$('#divCriteria').hide();
HoldOn.close();
if (status == "error") {
var msg = "There was an error: ";
$("#divResults").html(msg + xhr.status + " " + xhr.statusText);
$('#divCriteria').show();
$("#cmdSubmit").removeAttr('disabled');
}
});
}
Related
So I'm trying to use ajax to put content into a div, and trying to have it change all internal links before it adds the content so that they will use the funciton and load with ajax instead of navigating to another page. My function is supposed to get the data with ajax, change the href and onclick attributes of the link, then put it into the div... However, all it's doing is changing the href and not adding an onclick attribute at all. Here's what I was using so far:
function loadHTML(url, destination) {
$.get(url, function(data){
html = $(data);
$('a', html).each(function(){
if ( $.isUrlInternal( this.href )){
this.onclick = loadHTML(this.href,"forum_frame"); // I've tried using both a string and just putting the function here, neither seem to work.
this.href = "javascript:void(0)";
}
});
$(destination).html(html);
});
};
Also, I'm using jquery-urlinternal. Just thought that was relevant.
You can get the effect you want with less effort by doing this on your destination element ahead of time:
$(destination).on("click", "A", function(e) {
if ($.isUrlInternal(this.href)) {
e.preventDefault();
loadHTML(this.href, "forum_frame");
}
});
Now any <a> that ends up inside the destination container will be handled automatically, even content added in the future by DOM manipulations.
When setting a function to onclick through js it will not show on the markup as an attribute. However in this case it is not working because the function is not being set correctly. Easy approach to make it work,
....
var theHref=this.href;
this.onclick = function(){loadHTML(theHref,"forum_frame");}
....
simple demo http://jsbin.com/culoviro/1/edit
My problem is that I got 2 aspx controls generated like this :
<a id="sortByDate" href="javascript:__doPostBack('sortByDate','')">Date</a>
<a id="sortByLastName" href="javascript:__doPostBack('sortByLastName','')">Last name</a>
so those links allow you to sort the results. I'm trying to put this in a combobox instead of using links.
So I made it like this
<select id="sortBySelect" onchange="javascript:sortBy(this);">
<option value="sortByLastName">Last name</option>
<option value="sortByDate">Date</option>
</select>
with this javascript function
function sortBy(sel) {
var id = sel.value;
$("#" + id).trigger("click");
}
So when you change the selected element in the combobox I want to trigger the click event on the link to call the dopostback to sort.
It does nothing so far. I tried "click", "onclick", "onClick" and nothing works. Unfortunately, this is for IE quirks mode.
I know, this is really not elegant, but I'm really short in time and I need something quick and dirty. I will make an aspx control eventually to handle this nicely.
Any ideas how I could make this work in ie quirks mode?
Thank you
Try changing the location of the page:
document.location = $("#" + id).attr('href');
why don't you just fire the __doPostBack directly:
function sortBy(sel) {
var id = sel.value;
__doPostBack(id,'');
}
Use:
function sortBy(sel) {
var id = sel.value;
alert($("#" + id).length);//just for conforming that the element exists.
$("#" + id).click();}
Actually, jQuery only triggers any event bound to an element. You are trying to call the href action.
If you don't want to change the markup, you could try this solution.
Otherwise, you will have to change your html markup to bind javascript events & then try triggering it.
Good luck!
Everything works as intended!
JSFiddle proof.
Make sure you have an element with the id sortById and sortByLastName !
JavaScript/jQuery
$(document).ready(function(){
$('#sortByDate').click(function(){
alert('Sort By Date Click Event fired!');
})
});
function sortBy(sel) {
var id = sel.value;
$("#" + id).trigger("click");
}
Alternative
Force the window.location change
JavaScript/jQuery
function sortBy(sel) {
var id = sel.value;
window.location = $("#" + id).attr('href');
}
Note: You won't see any change in JSFiddle:
Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log
I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .
Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.
In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.
try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});
I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)
You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});
Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});
I have a webpage with a number of div elements such as this one:
<div id='ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA'>
</div>
I would like each div element to call a javascript function when it has loaded, to fill in the div. Ideally I would have liked to do
<div id='ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA'
onload=getcontent('ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA');>
</div>
but of course, onloads are not allowed for div elements. Is there a way to do this? I have read in a number of places that jQuery can help for this, but I can't figure out how to code it up. Any help would be very much appreciated!
To do it without jquery, you just need to set the onload for the window, and tell it what to do with each div. But jquery makes this much simpler.
So without:
window.document.onload = function() {
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
divs[i].text("blah blah blah");
}
};
It might be innerHTML. I'd have to double check. But that's the gist. With jquery:
$(function(){
$("div").text("blah blah blah");
};
This of course assumes each div gets the same text. If you want it to be based on ID or class, you most certainly want jquery.
PS - Most web pages try to avoid placing javascript event handlers in the actual HTML. If yous set up the event handlers on load, there's no need and the code is cleaner. Jquery definitely helps on this.
If you're basing the content on the ID of the div, a slight modification to Anthony's code should work
document.onload = function() {
var divs = document.getElementsByTagName("div");
for(var i = 0; i<divs.length;i++){
divs[i].innerHTML = getContent(divs[i].id);
}
I would assign a class to the div's that you want to 'autoload' their own content. This makes the markup clearer and the JavaScript more concise.
$(function() {
$('.autoload').each(function() {
// Use AJAX
$.get("service.php", {id: this.id} function(response) {
// Handle server response here
});
// Or a local data island
this.innerHTML = getDataById(this.id);
});
});
With jQuery:
You should consider using $.load() to retrieve html content. It's slightly easier to use than $.get(). Altho it'll use POST semantics if you supply paramters...
In any event, do you really want to make separate calls back to server for each div? .. Perhaps you should consider a single call that sends the accumulated set of div id's awaiting content to a your web-service function, that then subsequently returns a json structure that you can walk thru at success filling divs all in one shot ..
Something like (not-tested!):
$(function() {
var ids = [];
$('div.autoload').each() { function() { ids.push($(this).attr('id')); });
$.get('service.php', {ids: ids}, function (response) {
$.each(response.perdiv, function (i, c) {
$('div#' + c.id).html(c.html);
});
});
});