Javascript syntax for jQuery .load() function - javascript

I've just attempted to make a simple script to use ajax to load a new part of a page. The class remove/add to change the relevant text colour works fine. However, the new html does not seem to appear. I have a feeling this is to do with my general js syntax but I can't work it out.
Javascript:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#page_menu a").click(function() {
$("#page_menu p").removeClass("current");
$(this).children().addClass("current");
var project = $(this).attr("name");
var loadUrl = project + ".html";
$("#project_image").load(loadUrl);
return false;
});
});
</script>
An example of an anchor tag in the html would be:
<a name=example href="#">Example</a>
The html file I'm looking to load would be called "example.html" and the code in it:
<h1>Hello</h1>
I'm sure it's pretty straight-forward but I'm just not seeing it!
Cheers,
Rich

I would use the href of the anchor directly:
Example
<div id="project_image"></div>
And then AJAXify it:
$(function() {
$('#page_menu a').click(function() {
$('#page_menu p').removeClass('current');
$(this).children().addClass('current');
$('#project_image').load(this.href);
return false;
});
});

Anchor's most certainly do have a name attribute, so that part would be okay.. but to make things cleaner, change your anchor to:
Example
For length sake you can use shorthand syntax for $(document).ready, and also do the class changes in one chain. Then just load the page specified in the href and to see if the request actually worked, add a callback, like so:
$(function() {
$("#page_menu a").click(function(e) {
$("#page_menu p").removeClass("current").filter(this).addClass("current");
$("#project_image").load(this.href, function(res) {
// This will allow you to see the response from the server without having to dig through requests
// If you don't have a console for some reason, just change this to alert()
console.log(res);
});
e.preventDefault();
});
});

Related

How to pass `this` object to function through anchor link and convert it to jQuery object?

I'm having trouble with something that I'm trying to simplify. When a link is clicked, I want its CSS to be updated via jQuery. My main question is, how can I take Javascript's this object and convert it to a jQuery object for easier handling?
Here is what my code looks like:
<!-- HTML -->
load some page
load other page
// JS
function load(url, linkObj) {
loadPageWithURL(url);
$(linkObj).css('text-decoration', 'underline');
}
However, this does not work. Obviously I'm doing more than an underline when a link is selected, but you get the idea. Am I using this wrong or is it just a matter of converting the raw JS object to an object recognized by jQuery?
That function would work fine ($(linkObj) is correct), but you have your script in the href instead of on onclick attribute. So it won't ever execute.
Change:
load some page
load other page
To:
load some page
load other page
Don't use inline events! Use jQuery to bind them.
<a class="load" href="page.php">load some page</a>
<a class="load" href="other.php">load other page</a>
Then in JavaScript
$(function(){
$('.load').click(function(e){
e.preventDefault();
loadPageWithURL(this.href);
$(this).css('text-decoration', 'underline');
});
});
UPDATE: If new links are being added after the page is loaded, you need to use:
$(function(){
$(document).on('click', '.load', function(e){
e.preventDefault();
loadPageWithURL(this.href);
$(this).css('text-decoration', 'underline');
});
});
One of the advantages of using jQuery is that you can easily write unobtrusive JavaScript, it mean that you don't need to mix HTML with JavaScript. You can improve and achieve you requirements by refactoring your code as follows.
The HTML:
load some page
load other page
And your JavaScript code in one place:
jQuery(function($) {
$(document).on('click', 'a', function() {
var $link = $(this);
load($link.attr('href'), $link);
return false;
});
});
Note: The previous code will catch all links, if you want don't want to do this, you can add particular class name. Suppose the class name is load then the code should be rewritten as follows:
The HTML:
<a class="load" href="page.php">load some page</a>
<a class="load" href="other.php">load other page</a>
And your JavaScript:
jQuery(function($) {
$(document).on('click', '.load', function() {
var $link = $(this);
load($link.attr('href'), $link);
return false;
});
});
If you have any particular related to the code provided, put it on the comments.

Is there a way to use onclick without really onclick event?

I am having this code:
Add
is there any way to make an alert whenever the user will press this button without changing the code or adding onclick event?
You can simple overwrite the attribute with JavaScript:
// Select the targeted element(s), in this case the first <a> element
// Note: You will need to replace this by a code that works
// for your actual markup!
document.getElementsByTagName("a")[0].onclick = function() {
alert("hi");
return false;
}​​​;
Demo: http://jsfiddle.net/WNZAP/
As the OP states that they are not allowed to change the HTML, and that jquery is not available to them.
Not having an 'id' on the link makes life very difficult. So the following code presumes the link is the very first one on the page...
Place this javascript into the <head></head> section of your page...
<script type="text/javascript">
window.onload = function() {
document.getElementsByTagName("a")[0].onclick = function() {
alert("Hello World");
return false;
}
}
</script>
See Live JSFiddle Demo
It's not possible to trigger an action without an event. But if I get your question right you want to trigger an alert without changing the HTML.
The easiest way would be by using a JavaScript library like jQuery. So load the library either by downloading it and placing it in your project or through the Google CDN:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
And then do something like this:
<script type="text/javascript">
$(document).ready(function(){
$(".submitme").click(function(){
alert("hello world");
});
});
</script>

GET Request is driving me to drink

So heres the deal. I've got an html file, with an id="followers". I'm trying to make a get request with jQuery to get the xml tag from the twitter api:
(http://api.twitter.com/1/users/show.xml?screen_name=nightoutinc
and update the id with the accurate info.
I'm not getting any console errors with my jquery, which leads me to believe everything is hooked up right, I'm just not implementing the get request properly.
My Jquery looks like this:
(function ($){
getFollowers = function(){
$.get("http://api.twitter.com/1/users/show.xml?screen_name=nightoutinc", function(data){
$("followers").follower_count(data);
});
};
});
my html head looks like this
<script type="text/javascript" src="javascripts/jquery.js"></script>
<script type="text/javascript" src="javascripts/getfollowers.js">
$(document).ready(function(){
getFollowers();
});
</script>
please tell me, what is wrong?!?
-brian
Looks like you have scope issues. And it doesn't look like your function is being called; only defined. Try wrapping it up into one parent function that actually gets called.
(function($) {
function getFollowers() {
// Implementation here.
}
$(document).ready(function() {
getFollowers();
});
})(jQuery);
Your jquery object selecter seems wrong
$("followers")
Should be
$("#followers")
Notice the pound sign which indicates ID
did you define follower_count?
I guess it should be $("followers").html(data); NOT $("followers").follower_count(data);
You said the response was XML right? Then data is going to be an XML DOM not a string or HTML you can jsut insert into your page.
I can only find the docs for JSON but assuming the XML has parity:
$(function(){
$.get('http://api.twitter.com/1/users/show.xml?screen_name=nightoutinc', function(xml){
nbFollowers = $(xml).find('followers_count').text();
$('#followers').html(nbFollowers ? nbFollowers : 0);
});
});

Any ideas as to why this jQuery does not work?

I have an HTML page where a click event is captured and hides #testContent. I put the HTML and Javascript in a jsFiddle here: http://jsfiddle.net/chromedude/VSXY7/1/ . For some reason in the actual page the .click() does not work, but in the jsFiddle works. Does anybody have a clue why this would be?
I have ensured that the jQuery and Javascript file were both correctly attached and show up in the Webkit Inspect and Firebug. I am not getting console errors either. It's quite confusing.
UPDATE:
You can check out the actual page here: http://blankit.co.cc/test/77/
It looks like your javascript is not loaded correctly.
<script type="text/javascript" src="../../includes/jquery.js"></script><script type="text/javascript" src="../../includes/navbar.js"></script><script type="text/javasript" src="../../includes/study.js"></script>
You can put some alert() function inside your javascript file to make sure it is loaded correctly.
Your script tag has a typo in the type change it to text/javascript you are missing a letter.
Change study.js from
$(function(){
console.log('hello');
alert('hello');
/*var testContent = $('#testContent').val();
var contentArray = testContent.split(" ");
$('#studyTestLink').click(function() {
$('#testContent').hide();
alert('hello');
});*/
});
to
$(function(){
$('#studyTestLink').click(function() {
var testContent = $('#testContent').val();
var contentArray = testContent.split(" ");
$('#testContent').hide();
alert('hello');
});
});
I added your code to a page (using jquery 1.5.2) and it works fine. Don't you have any other code that could be breaking it?

Adding an anchor to generated URLs

I have tried finding a simialr example and using that to answer my problem, but I can't seem to get it to work, so apologies if this sounds similar to other problems.
Basically, I am using Terminal Four's Site Manager CMS system to build my websites. This tool allows you to generate navigation elements to use through out your site.
I need to add a custom bit of JS to append to these links an anchor.
The links generated are similar to this:
<ul id="tab-menu">
<li>test link, can i rewrite and add an anchor!!!</li>
</ul>
I can edit the css properties of the link, but I can't figure out how to add an anchor.
The JQuery I am using is as follows:
<script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// everything goes here
$("#tab-menu").children("li").each(function() {
$(this).children("a").css({color:"red"});
});
});
</script>
Thanks in advance for any help.
Paddy
sort of duplicate of this:
How to change the href for a hyperlink using jQuery
just copy the old href and add anchor to it and paste that back
var link = $(this).children("a").attr("href");
$(this).children("a").attr("href", link+ "your own stuff");
A nice jQuery-based method is to use the .get(index) method to access the raw DOM element within your each() function. This then gives you access to the JavaScript link object, which has a property called 'hash' that represents the anchor part of a url. So amending your code slightly:
<script type="text/javascript">
$(document).ready(function(){
// everything goes here
$("#tab-menu").children("li").children("a").each(function() {
$(this).css({color:"red"}).get(0).hash = "boom";
});
});
Would change all the links in "#tab_menu li" to red, and attach "#boom" to the end.
Hope this helps!
I can now target the html by using the following:
$(this).children("a").html("it works");
I assumed that:
$(this).children("a").href("something");
would edit the href but I am wrong.
Paddy
I am not sure for the answer, I dint try
$("#tab-menu").children("li").children("a").each(function() {
// $(this).css({color:"red"}).get(0).hash = "boom";
var temp_url = $(this).href +'#an_anchor';//or var temp_url = $(this).attr('href');
$(this).attr('href', temp_url);
});

Categories

Resources