Why is my $(this).prop('class') not working? - php

Here is what i want: I have multiple <h3> tags that are being uses as a link to reveal answers to FAQ's. Also I have added a form in case that the user did not see any question of interest on that page. The link for the form is at the bottom of the page. Now when the user click on the show form link I would like the window to scroll down to the bottom. I have done this, however when I click on any of the link the window also scrolls to the bottom. I want when the user clicks only on the show form link that the window scrolls.
here is what I have so far:
<body>
<?php
$array = array("link 1","link 2","link 3");
foreach($array as $link)
{
echo "<h3 class='link'>".$link."</h3>";
echo "<div>";
//information to be displayed
echo "</div>";
}
?>
<h3 class="forms">Show Form</h3>
//form information here
</body>
here is the javscript:
<script>
$(document).ready(function(){
$('h3').click('bind',function() {
$(this).toggleClass('open').next().slideToggle(500,function(){
var i = $(this).prop('class');
if(i == 'forms')
{
$("html, body").animate({scrollTop: $(document).height()}, "slow");
}
});
});
});
</script>
I have added an alert to verify my output and when I click on <h3 class="forms"> the alert is blank but when I click on the others the alert showed "link". Can someone help me figure out why the alert is showing blank when I click on the <h3 class="forms"> tag?

You are echoing your LI with the link class, instead of $link.
Also, use
if ($(this).hasClass("forms"))

.prop() should really only be used when accessing the DOM element's properties and not attributes (like class or style, width, etc.). If you want the class, use .attr('class') instead (or, as others have mentioned, you can use .hasClass() to test (with jQuery) if an element has a specific class aplied).
to follow-up on .prop vs .class:
Foo Bar link
var a = document.getElementById('foolink'),
$a = $(a);
$a.prop('href') // like directly calling a.href
$a.prop('id') // again, like directly calling a.id
$a.attr('class') // where as it's actually a.className

Related

expand/collapse div (toggle) when clicking on header

I have the following jQuery code to toggle the view of more information in a div.
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
});
The code works to toggle the view of displaying more information when the submission header is clicked. The div IDs of $moreInfo are dynamically created.
$moreInfo = $bidValue.''."_status";
echo "<div class='expandCollapse' id='$bidValue'>Submission</div>";
echo "<div id='$moreInfo'>$displayComments</div>";
However I want to open only one view/div at a time. If a div is open when a submission is clicked it should be closed before the other one is opened.
I've tried several things but it closes or hides all divs. Searching the web only show a solution using anchor tags.
Any thoughts...?
Thanks.
To achieve this you can put a common class on the second div element to allow you to hide them all before showing the next, like this:
echo '<div id="$moreInfo" class="expand-area">$displayComments</div>';
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#" + bidValue + '_status').slideToggle(500)
$('.expand-area').not(expandArea).hide();
});
Also note that you can make your code much more simple and generic by usnig DOM traversal to select the elements, instead of building selector strings based on related id attributes, like this:
$(".expandCollapse").click(function () {
var expandArea = $(this).next('.expand-area').slideToggle(500);
$('.expand-area').not(expandArea).hide();
});
The code above assumes that the elements are siblings, but you can easily amend the next() to traverse however is required.
Assuming the header and content divs are siblings you may use:
$(.expandCollapse + div)
// All <div>s that are immediately after an .expandCollapse
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
$('.expandCollapse + div').not(expandArea).hide();
});
$('[id$="_status"]').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='expandCollapse' id='bidValue1'>Submission1</div>
<div id='bidValue1_status'>displayComments</div>
<div class='expandCollapse' id='bidValue2'>Submission2</div>
<div id='bidValue2_status'>displayComments</div>
<div class='expandCollapse' id='bidValue3'>Submission3</div>
<div id='bidValue3_status'>displayComments</div>

get value from a link without clicking it?

I am trying to show a jQuery alert by hovering on different links with different ids.
I want to tailor the alert based on each link hovered over. These links are created dynamically from a table...
Each link has a different id attribute, so I was thinking to have alert for each without having to click on the link.
For example: a link might have index.php?id=1 So I want to show an alert on hover that says This is an alert for link 1, etc.
Edit 1:
The div:
echo '<div class="trigger">';
echo "<a class='trigger' href='".INDEX.'?categ='.$_GET['categ'].'&action='.$_GET['action'].'&subaction=viewlevels'.'&levelid='.$compi['Competence_ID']."'>";
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("What is this?").'"/></a>';
echo '<div id="pop-up">';
echo" <h3>Pop-up div Successfully Displayed for".$_GET['levelid'].
"</p></div>";
Edit 2:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$('.trigger').mouseover(function() {
alert("You are hovering over " + $(this).attr('href').match(/id=([0-9]+)/)[1]);
});
</script>
But it always tells me that levelid is undefined..( of course because the form has not been sent)
Yes, you can use jQuery's mouseover() for this:
$('.trigger').mouseover(function() {
alert("This is an alert for link " + $(this).attr('href').match(/id=([0-9]+)/)[1]);
});
You should change from using ID's to using a common class.
to bind jquery function on a link over of container child element use below code
$(document).ready(function(){
jQuery("#container a").each(function() {
jQuery(this).mouseover(function() {
alert(jQuery(this).attr('href'));
});
});
});
$('#aid').mouseover(function(){alert('whatever you want'+this.id)});
documentation http://api.jquery.com/mouseover/
You can also use .hover and that has two callback one when hover-over and one for hover-out.
$('a').hover(function(){
alert($(this).attr('href'));
},function(){
alert('hover out');
});
If you are creating links dynamically, then associate attribute class (say sampleclass) and attribute id as (concatenate "link " and id value from database) with each link
Now
$(document).redy(function(){
$(".sampleclass").hover(function(){
alert("This is " + $(this).attr("id"));
});
});

scrollTo just works on the first link

I've got this lines of code that, when the user clicks on the link, the page should scroll down to the respective anchor.
Turns out that it only works with the first link. The others just fire this exception
Uncaught TypeError: Cannot read property 'slice' of undefined
Here's the code
jQuery
$(document).on('click','#scrollTo',function(){
var to = $(this).attr('class');
//alert(to);
//This allways print the correct class name
$(window).scrollTo('div #'+to,'1000');
});
PHP
<ul id="source">
<?php
$sourceRCS = $source->getAllSources();
foreach($sourceRCS as $src)
{
echo '<li data-value="'.$src->name.'">'.$src->name.'</li></a>';
}
?>
</ul>
foreach($sourceRCS as $src)
{
echo '
<div class="custom-label-src">
<div id="'.$src->name.'" class="span12 label-title-src">
'.$src->name.'
</div>
</div>';
}
What am I doing wrong?
Thank you in advance
ID's are supposed to be unique, but you repeat #scrollTo. Try using a CSS class as your target instead.
var to = $(this).attr('class');
$(window).scrollTo('div #'+to,'1000');
You are selecting a class and assigning it to "to". Then you take the class and convert it into an ID in the next line.
Your selector should be like this:
var to = $(this).attr('class');
$(window).scrollTo('div .' + to,'1000');
Html Id's have to be unique. Like previously suggested, try using classes instead. Also, try capturing the event target and scrolling to it:
$(document).click(function(evt){
var target = evt.target;
$(window).scrollTo(target, 1000);
});
However, this will scroll to everything that a user clicks on. A better solution is to set up click event handlers on only the anchor tags that you want to scroll to:
$("#source a").click(function(evt){
evt.preventDefault();
var target = $(evt.currentTarget);
$(window).scrollTo(target, 1000);
// More code here...
});

Show Hide Div Dependent on Get ['status']

Hopefully someone will know how to do this...
I would like the show/hide to work dependent on the the image/icon clicked.
For example if Request Icon is clicked, the colorbox popup will be displaying the Request and Offered divs.
Whereas if the Accepted Icon is clicked, the colorbox popup will display Accepted and Offered Divs but hides the Request div.
Here's a few in the PHP:
<div <?php if($_GET['status']=="Requested"){ echo "class=iconActive";}else {echo "class=iconInactive";}?>>
<a href="/index.php/agent-appointment-request-list/?status=Requested">
<img src="components/com_agent/images/requestedIcon_s1.png" id="requestedIcon" alt="" /></a>
<div class="iconTitle">Requested</div>
</div>
Here's the jquery for show/hide that I have:
$(".slidingDivReq").show();
$("#show_hideReq").show();
$('#show_hideReq').click(function(){
$(".slidingDivReq").slideToggle();
});
Update: Here's the section for the content that'll be show/hidden. :
<div class="AppointmentTitleFirst">
<img src="components/com_agent/images/req_appt_title_s1.png" class="ApptIcon"></img>
<h1>Requested Appointment # <?php echo $this->appointment->id;?> Status:<?php echo $this->appointment->status_name;?></h1>
<img src="components/com_agent/images/dropdown_arrow_s1.png" class="ApptDropDownArrow1" id="show_hideReq"></img>
</div>
<div class="clearFloat"></div>
<div id="requestedAppointmentContent" class="slidingDivReq">
Content here....
</div>
Pretty much, I'm not sure how to use the GET['status'] and use it with the show/hide. So if the GET['status'] == Requested, then the show_hideReq will be .show(), but my other divs in the colorbox will use .hide(); (unless it's a page that needs a few other divs to .show())
Hopefully someone will know.
I'm not sure how to use the GET['status'] and use it with the
show/hide
You can use a hidden element as a variable, sothat you can test your GET['status'] in jquery. Add this element in your php page:
<input type="hidden" id="StatusId" value="<?php echo GET['status']; ?>"/>
Then you can do this:
$('#div').click(function(){
var statusId = $("#StatusId").val();
If( statusId === 0){
//Do something
}else{
// Do something elese
}
});
You should send the status value in the url that redirect to this php page, for example from js file it would look like:
var url = "http://localhost/yourcurrentphpfile.php?Status=" + somevalue;
window.location.href = url;
or the clicked <a> tag in your php page that redirect to this page should has the href property looks like http://localhost/yourcurrentphpfile.php?Status=somevalue.
yourcurrentphpfile.php is the php page that containst the hidden input.
You'd better use $(element).css("dissplay","none"); to hide an element and $(element).css("dissplay","inherit"); to show it.
Also in your PHP you better use if (isset($_GET['status']) && !empty($_GET['status'])) to ensure you have a value. Also, you need to edit your ECHO instructions to:
echo 'class = "iconActive"';
and
echo 'class = "iconInactive"';
Following your code's logic,
$(function(){ //on page load
$("div.classActive").load(function(){
//Do whatever you want when the div is active such as show/hide elements
})
$("div.classInactive").load(function(){
//Do whatever you want when the div is inactive such as show/hide elements
})
})
Only of the 2 will be executed since when a page renders only one of them will exist.

Javascript Show/Hide DIV on click/toggle

I list a lot of users on my page and I use a php function to pass the user's id and return a div pop up that displays their online status, avatar, stats etc. The problem is that the code is currently set to show the layer onmouseover and hide the layer onmouseout. I would like the code to be onclick show, and second click (either toggle on the same link or click anywhere else on the page) hide the layer but I'm not sure how to accomplish that.
The current code I'm using I got from Dynamic Drive. (sorry my tab key won't work in this text box, not sure how to fix that. feel free to edit)
SKIP TO BOTTOM
Original Method:
Javascript part
<div id="dhtmltooltip"></div>
<script type="text/javascript">
/***********************************************
* Cool DHTML tooltip script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var offsetxpoint=-60 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function ddrivetip(thetext, thecolor, thewidth){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=thetext
enabletip=true
return false
}
}
function positiontip(e){
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20
var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000
//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"
//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.visibility="visible"
}
}
function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}
document.onmousemove=positiontip
</script>
PHP part
$username = "<a onMouseover=\"ddrivetip('<Center><font class=f2>$username</font><BR>$avatarl</center>
<table align=center><Tr><Td><b>Points:</b> <font class=alttext>$user_points</font>
<BR><B>Posts:</b> <font class=alttext>$user_posts</font><BR>$user_status</td></tr></table>
<BR><img src=$icons/add-user.png height=12> <a href=$cs_url/friends/add/$user>Send Friend Request</a>
<BR><img src=$icons/user_message2.png height=12> <a href=$cs_url/messages/compose/$user>Send Message</a>
<BR><img src=$icons/user_im2.png height=12> Instant Message')\"
onMouseout=\"hideddrivetip()\">$username</a>";
My primary reason for wanting the toggle/blur as opposed to mouseout is so that users have the chance to actually click the links inside of the div layer.
The reason why I am trying to stick to this script as opposed to other ones out there I've found is because it doesn't rely on unique ids or alot of css styles. With other scripts, when I click on one username, they all of the hidden divs on the page pop up, or at least all of them for that user. This seemed to be the best for showing just one at a time.
I decided to scrap the method above. I have a script that I also got elsewhere that I use to toggle a twitter-like login in. I was wondering how I could use it to toggle the user information layer.
Second Method:
Javascript
$(".users").click(function(e) {
e.preventDefault();
$("fieldset#users_menu").toggle();
$(".users").toggleClass("menu-open");
});
$("fieldset#users_menu").mouseup(function() {
return false
});
$(document).mouseup(function(e) {
if($(e.target).parent("a.users").length==0) {
$(".users").removeClass("menu-open");
$("fieldset#users_menu").hide();
}
});
PHP part
<div id='container' class='users_container'>
<div id='usersnav' class='usersnav'> <a href='<?php echo $cs_url; ?>/users/all' class='users'><span>Fans</span></a> </div>
<fieldset id='users_menu'>
content
</fieldset>
</div>
The problem with this method as I mentioned before is that when I click on the username link, ALL of the layers for ALL of the users display on the page appear. How can I make it so that only the child layer of the parent link is displayed? Also, is there a way to toggle the layer hidden when anywhere else on the page is clicked?
Starting from your old code I assume you had something like:
elem.onmouseover = showCard;
elem.onmouseout = hideCard;
Well, from there you just need to do something along the lines of:
elem.isShown = false;
elem.onclick = function() {
if( elem.isShown) hideCard();
else showCard();
elem.isShown = !elem.isShown;
}
This ended up being the best solution though there is still one thing I wish was different about it.
This is built upon Dan's response. The reason why it wasn't working before Dan was because the user information was inside tags, I switcher username to span and the content display. The problem after that was when I clicked on one username the layer would popup but it would remain until I clicked on the same link again. So multiple layers would sometimes be on at once.
The following closes the layer when a user clicks on the layer, outside the layer or on the original link. The one little snag is that when clicking on the original link to close the layer you must click twice.
Javascript
<script type="text/javascript">
$(document).ready(function () {
$(".username").click(function () {
$(this).children().toggle();
$('.tooltip_container').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$(".username").click(function () {
$(this).children().toggle();
});
});
$("body").mouseup(function(){
if(! mouse_is_inside) $('.tooltip_container').hide();
});
});
</script>
PHP
<span class='username'>$username
<div class='tooltip_container'>
<div class='tooltip'>
Content goes here
</div>
</div>
</span>

Categories