Selecting elements to show and hide, traversal issue! (jQuery) - javascript

I have been trying every combination under the sun of parent()/children()/find() and selector syntax to .show() an element of my webpage that i hid on document ready, but I just can't get it to work! I'd really appreciate it if someone could take a look..
If you go to the portfolio section you can see it live here -> http://holly.im/ .
In any case the html looks something like this:
<div id="portfolio">
<h1>Heading</h1>
<div class ="little_column">
<div class="project">
click
</div>
</div>
<div id="c++_games_engine_construction" class="big_column">
<?php include "projects/C++_game_engine_construction.php"; ?>
</div>
</div>
And the relevant jquery:
$(document).ready(function() {
//hide all the big_columns /
// project details within the portfolio page
$('#portfolio').find('.big_column').hide(); //This seems to be working
});
$(function(){
$('.project').click(function () {
var selectedProject =
$(this).children('a.projlink').attr('href');
$(this).parent().parent().find(selectedProject).show(); //My most recent attempt, I though maybe i needed to go up the heirachy then back down? But whatever i try it doesn't show.
return false;
});
});
That's it really, thanks!

Having the character + in the ID of an element causes jQuery to become confused because the + character is reserved for the Next Adjacent Selector.
If you remove those characters from your code, it works just fine. As was mentioned in one of the comments to this answer, since the href is essentially the ID of the item to be shown, you can select it directly.
HTML
<div id="portfolio" class="section">
<h1>Heading</h1>
<div class="little_column">
<div class="project"> click
</div>
</div>
<div id="c_games_engine_construction" class="big_column">
I'm hidden at first!
</div>
</div>
JS
$(document).ready(function () {
//hide all the big_columns /
// project details within the portfolio page
$('#portfolio').find('.big_column').hide(); //This seems to be working
});
$(function () {
$('.project').click(function () {
var selectedProject = $(this).children('a.projlink').attr('href');
$(selectedProject).show(); //My most recent attempt, I though maybe i needed to go up the heirachy then back down? But whatever i try it doesn't show.
return false;
});
});
jsfiddle

The issue is with the + in the selector. It needs to be escaped because it has special meaning in the Selectors API (and is invalid for an ID).
If you removed the ++ from the href and the id, it works.
Alternately, you can do .replace(/\+/g, "\\+")
var selectedProject = $(this).children('a.projlink').attr('href').replace(/\+/g, "\\+")
Off topic: You don't need two .ready() calls, which is what you have, but using different syntax.

As others have mentioned, your problem are the + characters mistreated by jQuery. So the simple solution is: do not use jQuery - or at least, not for the selector thing. Since every target you have is an id selector, we can easily change it to
$(document).ready(function() {
$('#portfolio').find('.big_column').hide();
$('.project').click(function () {
var selectedProject = $(this).find('a').attr('href'); // a littebit simplified
var el = document.getElementById(selectedProject.slice(1));
$(el).show();
return false;
});
});

Related

How do I click on a link without id

I'm not experienced in javascript. I'm trying to write a function in CasperJS, which uses javascript.
I'm trying to click on a link from a search result page. The <a href> tag does not have an id to it, but it is enclosed in a <h3 />, which is enclosed in a <div id="some_id"/>.
Essentially the code looks like this:
<div id="result_0">
<div />
<div />
<h3 class="...">
<a href="some_link">
.
.
</a>
</h3>
.
.
</div>
I want to know how to click that link in javascript.
I tried doing it like this:
document.getElementById('result_0').getElementsByTagName('div')[2].getElementsByTagName('a')[1].click();
But this doesn't seem to work. Can you guys help ?
Edit: Here is the link to my entire script: https://github.com/ctrl-shift-esc/randomamazonshopper/blob/master/myscript.js
You need a CSS selector and the thenClick method here. Something like this should work:
casper.thenClick('#result_0 h3:first-child a');
The following works for the html structure shown in the question (if you change the div's id from some_id to result_0):
document.getElementById('result_0').getElementsByTagName('h3')[0]
.getElementsByTagName('a')[0].click();
Demo (open the browser's JS console): http://jsfiddle.net/kyLXT/1/
Perhaps your code had the wrong indices in the square brackets?
Or you can do this to click the first link in the first h3 within the element with that id:
document.querySelector('#result_0 h3 a').click();
Or if you're concerned that there might not be a matching element:
var el = document.querySelector('#result_0 h3 a');
if (el)
el.click();
// optionally add an else here
Note that either way the code would need to be in a script block that appears after the elements in question and/or in a DOM ready or window onload event handler (the jsfiddle demo above put the code in an onload handler via the fiddle options on the left).
You can use the ID of the div holding the <h3>:
var oParentDiv = document.getElementById("some_id");
var arrHeaders = oParentDiv.getElementsByTagName("h3");
if (arrHeaders.length !== 1) {
alert("no header or more than one");
} else {
var oHeader = arrHeaders[0];
var arrLinks = oHeader.getElementsByTagName("a");
if (arrLinks .length !== 1) {
alert("no link or more than one");
} else {
var oLink = arrLinks[0];
oLink.click();
}
}

jQuery - how to determine which link was clicked

I have a simple piece of PHP which generates n copies of the following code:
<p class="ShowSDB_L2" class="center" onClick="FSD_L2('<?php print dbG;?>','<?php print $sLID;?>')">Click Here to See Data</p>
<div class="divSDB_L2">
</div>
It is generated using PHP, so the number of copies is unknown up front.
On another page I have the following Javascript (using jQuery)
function FSD_L2(dbG,SlID)
{
$(".divSDB_L2").load("test15.php?dbG="+dbG+"&SlID="+SlID).css('display','block');
}
When the text above (Click Here to See Data) is clicked, it should add the contents of test15.php between the the two DIV tags.
#Test15.php
<?php
$dbG = $_GET['dbG'];
$SlID = $_GET['SlID'];
print $dbG . " & " . $SlID;
?>
The problem I have is how to determine which of the links was clicked? At present, if I have three copies, and click one, all three copies are activated.
I hope I have made this clear enough. I'm sure there must be a simple way, but I'm quite new to Javascript/jQuery.
Like Brian said, you could just put the same class on all of your links and use the $(this) keyword in jQuery inside of a click function to find out which link was clicked.
Here's a basic example of changing link colors on a nav using this technique: http://jsfiddle.net/9E7WW/
HTML:
<a class="nav">Test</a>
<a class="nav">Test2</a>
<a class="nav">Test3</a>
<a class="nav">Test4</a>
Javascript:
$(document).ready(function(){
$('.nav').click(function(){
// change all to black, then change the one I clicked to red
$('.nav').css('color', 'black');
$(this).css('color', 'red');
});
});
Am not sure I fully understand what it is you are having difficulty with, but the following is how I would do it.
<p class="ShowSDB_L2" class="center" data-dbg="<?php print dbG;?>" data-slid="<?php print $sLID;?>">Click Here to See Data</p>
<div class="divSDB_L2"></div>
$(document).ready(function() {
$(document).on('click', 'p.ShowSDB_L2', function(evt) {
var $p = $(evt.currentTarget),
dbG = $p.data('dbg'),
slid = $p.data('slid'),
$div = $p.next();
FSD_L2(dbG, slid, $div);
});
});
function FSD_L2(dbG, SlID, $div)
{
$div.load("test15.php?dbG="+dbG+"&SlID="+SlID).css('display','block');
}
The click handler is not hardcoded to each p tag. Instead with each p tag we store the required data, ie dbg & slid.
The click handler is then attached once at document ready. jQuery abstracts over the various browsers and passes to its handlers the event object as its first parameter. This object can then be used to find the element on which the event occurred. Refer: http://api.jquery.com/on/
Finally, we fetch the required data from the clicked element, find the div that needs to be updated and then call your custom function.
Here is a cross-browser way to find the element (target) that triggered the event (e):
function getTarget(e){
// non-ie or ie?
e=e||window.event;
return (e.target||e.srcElement);
};
Add the complete URL to your link (or p in this case) using a data attribute:
<p class="ShowSDB_L2" class="center" data-loadurl="test15.php?dbG=<?php echo $dbG; ?>&SlID=<?php echo $SlID; ?>">Click Here to See Data</p>
<div class="divSDB_L2"></div>
Then do all the binding directly in your jQuery so you have direct access to the link that was clicked:
$(document).ready(function() {
$('.ShowSDB_L2').on('click', function(e) {
e.preventDefault();
$('.divSDB_L2').empty().load($(this).data('loadurl')).show();
});
});

Jquery, select and scroll next element

I've got a newbie jQuery question. I need to add a number of tiny text boxes with links to scroll up and down any overflowed content.
I've got it to work as follows, but need to rework it to handle repeated boxes of text on the page.
Javascript..
$(function() {
$('a.scrolldown').click(function(event) {
event.preventDefault();
$(".mytextbox").scrollTop($(".mytextbox").scrollTop() - 20);
});
});
With the markup...
<div class="news_col">
<p class="newscontrols">
<a class="scrolldown" href="#">down </a><a class="scrollup" href="#">up</a></p>
<div class="news_item_text mytextbox">
<p>Loren ipsum...</p>
</div>
</div>
I realise I could use maybe the 'next' selector but need a bit of help rewriting it.
You can use next() with $(this) to access the textbox after the .scrolldown anchor.
$(function() {
$('a.scrolldown').click(function(event) {
event.preventDefault();
$mytextbox = $(this).next(".mytextbox");
$mytextbox.scrollTop($mytextbox.scrollTop() - 20);
});
});

find ID of parent DIV and fade DIV out

Im trying to fade out a DIV when clicking a link within the DIV itself. Here is my code:
$(".hideinfo").click(function () {
var parentLink = $(this).parent().parent();
$(parentLink).fadeTo("slow", 0);
});
The reason I'm not specifying the ID directly is because I want to use this to fade out multiple DIVs with different ID's.
The above code was returning the ID when I setup an alert but not fading the DIV out or anything else I tried to so... any help here would be appreciated. The HTML is:
<div id="First-Block" class="item">
<p>text here</p>
<p>Back</p>
</div>
Thank you!
You should use fadeOut("slow") instead.
Try changing your code to:
$(".hideinfo").click(function () {
var parentLink = $(this).parent().parent();
$(parentLink).fadeOut("slow");
});
To improve this even further you can shorten your code to:
$(".hideinfo").click(function() {
$(this).closest(".item").fadeOut("slow");
});
Just to mention as well that by clicking on an anchor it will jump to the top of the page using #. I would take a look at .preventDefault()
You can also check out the API here -> http://api.jquery.com/fadeOut/
Use fadeOut() instead since your primary goal is to affect the overall visibiltity not a given opacity.
jsBin demo
$(".hideinfo").click(function( e ){
e.preventDefault(); // prevent default anchor link behavior
$(this).closest('.item').fadeTo(400, 0);
});
Additionally try to wrap the above into a document ready :
$(function(){
// code here.
});

How do I use colorbox to show hidden divs on my page without hardcoding?

I'm using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
This will show the div with the ID of 344.
However, because I'm trying to build a scalable and dynamic page with WordPress, I want to be able to grab the ID of my divs through a function, rather than hard code them in the jquery call.
I modified Jack Moore's example:
$("a[rel='example']").colorbox({title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
so that it looks like this:
$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
var elementID = $(this).attr('id');
return elementID;
}});
The problem with this is that the href property of the colorbox function is looking for a string with a # mark infront of the ID. I tried various ways of concatenating the # to the front of the function, including the # in the return value, and concatenating the # to the elementID variable. No luck.
I also tried using the syntax in Jack's example (with no luck) so that my return statement looked like this:
return "#'+elementID+'";
I think my basic question is: How do I use colorbox to show hidden divs on my page without hardcoding everything?
Thanks for your help,
Jiert
I didn't really like any of the answers given above. This is how I did it (similar but not quite the same).
I also fully commented it for people a bit new to Javascript and the colorbox plug in.
$(document).ready(function() { //waits until the DOM has finished loading
if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
$('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
$(url).hide(); //hides the lightbox content div
$(this).colorbox({
inline:true, // so it knows that it's looking for an internal href
href:url, // tells it which content to show
width:"70%",
onOpen:function(){ //triggers a callback when the lightbox opens
$(url).show(); //when the lightbox opens, show the content div
},
onCleanup:function(){
$(url).hide(); //hides the content div when the lightbox closes
}
}).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
//you could also use "return false" for the same effect but I proffered that way
})
}
});
And this is the html:
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
I think it would work with multiple lightboxes on the one page but I haven't tested it with that.
I'm facing the same issue. What does your html look like? meaning, how did you structure your "divs"
Mine looks like this:
Javascript:
<script>
$(document).ready(function () {
$("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
var elementID = $(this).attr('id');
return "#" + elementID;
}
});
});
</script>
And the html looks like (I tried changing the display:none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
return "#" + elementID;
will have the desired effect as David says.
This is the way I got it to work
HTML: (taken from the example in one of the answers)
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
Javascript:
$('a.lightboxTrigger').click(function(){
var ref = $(this).attr("href");
$.colorbox({ html: $(ref).html() });
$.colorbox.resize();
});

Categories