$(function () {
$(".links2lvl a").click(function () {
var page = this.hash.substr(1); /*in case of first link - works*/
/* var page = this.hash.substr(7); in case of second link - nope.jpg*/
$.get(page + ".php", function (gotHTML) {
$("#content").html(gotHTML);
});
});
});
<section class="tabs">
<ul class="links1lvl">
<li><a>About</a>
<ul class="links2lvl">
<li>Us</li>
<li>Personal</li>
So here I have two two sets of code. First is jQuery function, which extracts given PHP file and it's contents are shown in div with id="content".
The other is my 2 level list. In the second level you can see pages I'm trying refer to. The first link works just fine, jQuery successfully extracts the content and shows it given plave, but the second link in the folder about/ thats another story, the function doesn't seem to find it. The question is, how do I refer to .whatever from another file?
Most of the problems I see in code are based on attempts to solve challenges by adding more challenges to the code. :)
I would give a suggestion and I hope you don't mind: I would solve it by adding a "data-*" to each a tag to hold the reference you need to find using this.hash (or, maybe, use .each or .map) to loop through the elements and extract the proper URL to be used).
What happen is, this.hash will return "#who", but it is also a valid ID selector in jQuery (see more here). Hence this.hash will find "#who", but won't find "about/#personal" (because the hash element is not the first character of the string).
You could use string.split('#') to capture the string straight after the "#", then save it in - for instance -, the data-hash parameter at each a tag while constructing the HTML. Then it should be fairly easy to obtain the content needed for your application (once again, it is always about how to minimize challenges, instead of add them). ;)
Sadly I am no able to build a code sample now, but if you have difficulties following this idea, contact me and I will write a quick sample code for you.
Related
I am working on a website where I do not have direct access to all the source files, but can add extra functions using Javascript. What I am trying to do is create a button which adds "?action=delete" to the end of whatever the page's URL is, considering that this button (well, a link formatted as a button) will load on every page on the site (hence why I can't just put the URL straight into the function). I have already got to the stage where I can produce the button and make it look as I wish it to, and in the right position, but am struggling to get the href parameter to work with any page identifying Javascript I have already found. Here is what I have so far:
$('a.wikia-button.talk').after('<div><a class="wikia-button" title="Go to normal delete page" href="???">Delete</a></div>');
The three question marks are where I don't know what to put. One obvious problem I have found in trying to get this to work is to do with quotes: single and double quotes have both already been used, and so can't be used again within the href parameter (at least, not in any way I know of). This obviously makes it hard to identify a string to add the "?action=delete" to the end of the URL, and I'm guessing is the main problem causing my function to break in all the ways I've previously tried.
Any help you could give would be most appreciated! I would also like to point out that I'm not that good with Javascript, and usually just stick to altering others' functions. However, I haven't so far found any other person with this specific Javascript nestling problem to steal their code, so I hope you can help out!
~Imamadmad
First, quotes are no problem. I am a regular user at Wikia, and I know for a fact that you don't need quotes around any parameters in the url.
Second, you have two choices here: work out the correct href parameter, or use an onclick attribute.
Choice one: we first work out the href needed:
var where = window.location.href + "?action=delete";
and then we add the button, like so:
$('a.wikia-button.talk').after('<div><a class="wikia-button" title="Go to normal delete page" href=' + where + '>Delete</a></div>');
Choice two: we delegate an onclick event to the button:
$("div").on('click', "#deleteButton", function() {
var where = window.location.href + "?action=delete";
window.location.href = where;
});
and then we add the button, like so (note the absence of an href attribute):
$('a.wikia-button.talk').after('<div><a class="wikia-button" title="Go to normal delete page" id="deleteButton">Delete</a></div>');
My main mission: Is to get the text of the next and the previous objects to the chosen object - To display the image (and its titles) Previous & Next.
Before that I have a problem: to get text of a selected object, from an index to a variable.
The problem: Every time I pick a random object, the variable does not change but the text is added to the existing text in the index.
I made a DEMO, would appreciate your help.
$(document).ready(function hintProject(){
$('#nextProject, #prevProject').click(function(){
subtitle = null;
subtitle = $('#client-sub.active').justtext();
$('#next_target_title').text(subtitle);
alert (' text::: ' + subtitle );
});
});
It looks like jQuery simply can't find the objects you're specifying. I don't think the problem is with the snippet in the question. I think the problem is with your document ready function.
To debug, try simplifying your problem by cutting out all of the additional complexity of the setup script and just set up an HTML page that is in the state you want. It's much easier to understand 1 problem than 2 or more.
Also, try simplifying how you're specifying an active item: a single class on the portfolio item would make your life easier. Then you can specify css and such based on the parent instead of adding multiple classes to multiple things inside the each portfolio item.
I'm trying to write jQuery code to count the number of <img> elements contained on a site. The site is comprised of 4 separate HTML pages, all in the same folder on the server. Only one of these pages, "pics.html", loads the .js file that needs to perform this function (pics.html is the only page that needs to know how many images are on the site).
It's easy to get the <img> elements from pics.html, since pics.html is the page that loads the script:
var numImgs = $('img').length;
...but I'm confused as to how I would perform this same function in reference to a different page. Is it possible to specify the HTML page that the selector refers to?
I tried this, as a wild guess:
var numImgs = $('test.html:img').length;
Unsurprisingly, it didn't work. I googled for the answer, but couldn't find a solution - or if I did find one, I suppose I didn't understand it well enough to realize that it was the answer.
Thanks for any help you can offer!
To select an object from an external file, you'll need to use $.load().
Reference: http://api.jquery.com/load/
Try this
$(document).ready(function(){
$('#myDiv').load('/remotePage.html #TargetDiv', function () {
var elements = $('.class', this).length;
alert(elements);
});
});
I have a javascript link that references another .js file. I've been trying to output an image (for testing purposes), but I'm not sure what is the correct way to go about this.
alert("beginning");
//var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
//$('body').append(link);
//document.write("hi");
//document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("before function");
(function(){
alert("middle");
var links = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(links);
alert("after middle");
//alert($("img").attr("id"));
document.write("hi");
document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("end");
}());
I was able to alert beginning, all the way to middle. It seems like var links doesn't work. I'm trying to use HTML inside this .js file. Essentially, I want to be able to do some modal window, but I'm trying to output images for testing purposes right now.
Also, is this the correct way for jquery?
Thanks in advance!
Your code is a strange mix. Jquery code almost always needs to run after the page has loaded whereas document.write can never be used after the page has loaded.
You are incorrectly wrapping your jQuery in an immediate executing function. The proper wrap for jQuery is within :
$(document).ready(function(){
/* html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
or the shorthand version that does same thing:
$(function(){
/*html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
If you change all of your document.write to $('body').append(/* your content*/) and place all your code inside the above wrappers you will have much better success.
There is a wealth of information within the jQuery documentation and API. A good start point with more detail about the wrapping I've shown can be found here: http://docs.jquery.com/How_jQuery_Works
Your biggest problem is addressed in the other answer. You are improperly wrapping JQUery so essentially JQuery is not ready to be executed when it reaches your append statement.
It is unnecessary to wrap your html in a JQuery object (in this case):
var links = "<a href='http://juixe.com'>Hello, <b>World</b>!</a>";
$('body').append(links);
or simply:
$('body').append("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
In terms of best practice, using append, appendTo or prepend are good options depending on the context. You could also use:
$("body").html("/*Your HTML here*/")
At the end of the day you have many options but avoid document.write at all cost. The non-JQuery approach would be to use .innerHTML with a DOM element. This is also a good approach in the absence of JQuery.
First of all I would like to say that while this is the first time i post here these boards have helped me much.
With that said, I have got a strange issue regarding AJAX and scripts.
You see, in my web application i used custome JS context menus. Now each of them menus is implemented with specific features depending on the object and if the object exists.
E.x : if we got an upper menu place holder but no upper menu the context menu will have one option which is "add menu".
But say we already have the upper menu the context menu will have different options such as "edit menu" etc...
so far so good, however, say we have an upper menu place holder and no menu and then we added the menu (still no refresh on the page) i need to generate a new context menu and inject it right? so i do just that along with the new menu i just built.
all that code goes into the SAME div where the old context menu script and upper menu place holder were so basicaly they are overwriten.
Now the menu itself is in HTML so it overrides the current code the JS however acts wierd and will show now 2 context menus the old one and the new one even though i overwrite it's code.
I need to some how get rid of the old context menu script without refreshing the page.
Any ideas?
P.S
all the JS are dynamicaly generated if that makes any difference (i dont think it does.)
Well after some head breaking i figured it out..
(the problem not the solution yet) this is the ajax function right?
$.ajax({
type: "GET",
url: "../../../Tier1/EditZone/Generate.aspx?Item=contentholder&Script=true",
dataType: "html",
success: function (data) {
$('#CPH_Body_1_content_holder').html(data);
}
});
now they function uses a page with an event handler, that event handler reutnrs the data as followed response.write(answer) it just hit me that when you use response.write it sends the code after it's been compiled and ran in our case at page Generate.aspx.
so the script will run but not in the page i intended it to run and because of that i cannot overwrite it... how silly of me.
what i think ill do it return the data as an actualy string and then and only then inject the code into the container div.
ill let you folks know if that works out.
cheers and thanks for the advice these forums rock.
No matter what anyone says, do not use EVAL. It's evil and will give you memory issues if used more than a few times on a page.
See my soluition here: trying to call js code that is passed back from ajax call
Basically, create a div with the ID of "codeHolder" and voila. You'll basically want to pass your HTML and JS back to the AJAX receiver (separated by a separator), parse it on the JS side, display the HTML and put the JS Code in your javascriptCode variable.
//Somehow, get your HTML Code and JS Code into strings
var javascriptCode="function test(){.....}";
var htmlCode="<html>....</html>";
//HTML /////////////////////////////////////////
//Locate our HTML holder Div
var wndw=document.getElementById("display");
//Update visible HTML
wndw.innerHTML = htmlCode;
//Javascript ///////////////////////////////////
//Create a JSON Object to hold the new JS Code
var JSONCode=document.createElement("script");
JSONCode.setAttribute("type","text/javascript");
//Feed the JS Code string to the JSON Object
JSONCode.text=javascriptCode;
//Locate our code holder Div
var cell=document.getElementById("codeHolder");
//Remove all previous JS Code
if ( cell.hasChildNodes() )
while ( cell.childNodes.length >= 1 )
cell.removeChild( cell.firstChild );
//Add our new JS Code
cell.appendChild(JSONCode);
//Test Call///////////////////////////////////////
test();
This code will replace all previous JS code you might have put there with the new JS Code String.
Thanks for the replies.
Dutchie - that's exactly what I did. now the thing is the HTML is properly overwritten (I didn't use append I overwrote the entire div) and yes the javascript just keeps on caching...
I tried to disable browser cache and still the problem persists i get multiple context menu per item the more I ran the ajax function...
Jan,
My AJAX function builds a div tag and script tags and places them into another container div tag in the page.
What's suppose to happen is that every time the AJAX runs the code inside the container div is overwritten and you get an updated version.
the div inside the container div is overwritten yet the script tags somehow are cached into the memory and now each time the out jQuery function calls the context menu i get multiple menus...
I don't think code is needed but I will post it tomorrow.
Any ideas?