Jquery receive parameter from cookie - php

I'm creating a menu that is nested within
<a href="#">
<div class="container"> </div>
<div class="title"> </div>
<div class="Chapter"> </div>
</a>
my PHP foreachloop : tells me how many of these container elements I have could be 10 or 20.
what i'm trying to do is use Jquery to tell me what the child number of the menu item I clicked on. currently i'm using
var count2 = $(this).parent().index();
Then i'm saving the parameter into a cookie, with createCookie("menu",count2);
the cookie is setting correctly and now contains a string say "10".
my question is: which jquery function can I use to receive the parameter of the child
number of the menu items and add a class to that menu item.
something along the lines of
if (readCookie("menu") != null) {
$("a .container:nth-child(readCookie("menu")").removeClass("").addClass("active");
}

Try this. eq(x) returns the x-th result of your jquery selector.
$("a .container:eq(" + readCookie("menu") + ")").addClass("active");

I don't know what plugin you're using to read/write cookies, but the following code works with this plugin...
https://github.com/carhartl/jquery-cookie
var menu = $.cookie("menu");
if (menu) {
$("a .container:nth-child(" + menu +")").addClass("active");
}
if readCookie in your example is correct then you want this...
var menu = readCookie("menu");
if (menu) {
$("a .container:nth-child(" + menu +")").removeClass("").addClass("active");
}
I removed removeClass("") as that wasn't doing anything.

Related

Executing a jQuery script for each file and then print the results, BUT getting the first result multiple times

I'm trying to get the first link of each page using $('.yuRUbf a')[0].href;, however, this code gets the data of all pages, and then prints the link of the first page multiple times.
What am I doing wrong?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
function pageNum($pageNum) {
include $pageNum.".html";
?>
<script>
$(document).ready(function(){
const el = $('.yuRUbf a')[0].href;
console.log(el);
});
</script>
<?php
}
pageNum("1");
pageNum("2");
?>
EDIT:
Let me explain in another way: I have 5 html pages, each html page includes 10 links, I want the first link of each html page.
So I used the jQuery script to extract the href attribute value which is the link, however, instead of extracting the first link of each page, it is extracting the first link of the first page 5 times as I have 5 files.
Given that the existing code returns links for all pages, I'll assume that each "page" contains something similar to
<div class='yuRUbf'>
...
<div>
In this case, you can collate all the first links into an array using a single call at the end (ie not inside the pageNum loop)
var links = $(".yuRUbf").map((i,e) => $(e).find("a")[0].href).toArray()
(if you're passing this to something else, eg links.addClass("active") then don't use the .toArray())
this is the equivalent of, if you prefer/need a loop rather than an array:
$(".yuRUbf").each(function(i, e) {
var el = $(this).find("a")[0].href;
console.log(el);
});
Example:
$(function() {
const first_links = $(".yuRUbf").map((i,e)=>$(e).find("a")[0].href).get();
console.log(first_links)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='yuRUbf'>
<div>
<a href='l1'>l1</a>
</div>
<a href='l2'>l2></a>
<a href='l2'>l2</a>
</div>
<div class='yuRUbf'>
<div>
<a href='l12'>l12</a>
</div>
<a href='l22'>l22></a>
<a href='l22'>l22</a>
</div>

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>

My mess that I'm trying to do with PHP, MySQL, jQuery and css

Let's see if I can explain what I'm trying to do here..
I've got a MySQL Database with some info stored in it. I am using PHP to query the database, pull my selected entries out, put each one into a separate <div> (with Bootstrap framework). I have accomplished this part.
Below is a snippet of what I'm doing...
$query = "SELECT `quote`,`id` FROM `db`";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
echo ' <div class="panel panel-info">
<div class="panel-body text-muted" id="'.$row['id'].'">
'.$row['quote'].'
</div>
</div>';
}
Then I am wanting to use jQuery to add a css class on "click" to an individual <div> and be able to then use PHP to store the text of the "selected" <div> to a variable, for later use.
This is the part I am struggling with, I can not figure out how to separate each individual <div> specifically and have jQuery add the class to it, because the "id" of div differs with every result from the db query.
To add a class to a div when it is clicked -
jQuery
$('div').click(function() {
$(this).addClass('foo');
var divText = $(this).text(); // store to JavaScript variable
});
Now that you have the JavaScript variable stored you can send it to a PHP function via AJAX.
What I would do is add a class to the <div>s, and use that to attach the event.
<div class="panel-body text-muted click-panel" id="'.$row['id'].'">
Then in your JavaScript, do something like:
$(function(){
$('div.click-panel').click(function(){
var div_id = this.id,
div_text = $(this).text();
if(/* some condition eg. div_id === 5 */){
$(this).addClass('clicked');
}
});
});

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>

Jquery - Hide / Show - "Session" problem

I use this links and divs on my site:
<p>Menu1 | Menu2 | Menu 3|</p>
<div id="menu_1" class="mymenu">
</div>
<div id="menu_2" class="mymenu">
</div>
<div id="menu_3" class="mymenu">
</div>
And this jquery to hide and show the menu.
$('div[class*="mymenu"]').hide();
var current;
var showMenu = function(e) {
// read the id out of the clicked elements id ('navlink_ID')
var id = e.id.split('_');
$('div#menu_' + id[1]).show();
// store this element as new current visible
current = e;
}
// hide all menu elements
$('div.mymenu').hide();
$('a.navlink').click(function() {
if (this != current) {
// check if an element is visible -> hide it and show new menu
if (current) {
var id = current.id.split('_');
$('div#menu_' + id[1]).hide(200,showMenu(this));
} else {
showMenu(this);
}
}
return false;
});
How can i modify this code, if i reload the page, then the last visible DIV is stay visible. (i dont want to use query string for this. I try with jquery session but not work..)
Thank you for help...
Cookies would be the ideal way to persist your collapsible divs, ShopDev has an excellent tutorial on how to acheive the same thing as you are attempting to do, using the jQuery cookie plugin.
Basically you set a value in the cookie for each div that you want to persist and whenever the event happens you update the value in the cookie, e.g.:
$.cookie('menu_1', 'expanded');
Also you need to check when the page is first loaded the state of each div, e.g.
var menu_1 = $.cookie('menu_1');
if (menu_1 == 'collapsed') {
$('#menu_1').css("display","none");
};
Simplest pure JavaScript way: set cookie.

Categories