Toggling divs in javascript - php

I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks

Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");

To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});

Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});

Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.

Related

jQuery get value from while loop and display it in another div without click

How do I make jQuery get value from while loop and display it in another div?
I know I should do it with PHP, But I want to display it with only jQuery.
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"></div>
<? } ?>
$(document).ready(function() {
var getUrl = $('.get_url_comments').attr('href');
$(".show_url").text("Click This" + getUrl);
});
To do this you can set the text() of the .show_url element based on the following .get_url_comments. Try this:
$(document).ready(function() {
$(".show_url").text(function() {
return $(this).next('.get_url_comments').attr('href');
});
});
You should note though that it would be a much better idea to do this directly in PHP:
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"><? echo $commentresult['comment']; ?></div>
<? } ?>
Try with this..
$(document).ready(function() {
$('.get_url_comments').map(function(guc){
var el = $(guc);
var url = el.attr('href');
el.prev().text("Click This" + url);
// or
el.prev().html("Click This" + url);
});
});

Toggle function: Remember the position

I used the function toggle I would like that if I refresh the page, it remember the position of the toggle.
I try to use the session but I can't find the way to update the session (when the user want to see more or less).
Here is my code:
<script language="javascript">
function toggle(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src="more.png"">';
}else {
ele.style.display = "block";
imageEle.innerHTML = '<img src="less.png">';
}
}
</script>
<?php
if(empty($_SESSION["toggle"])){
$_SESSION["toggle"] = 'show';
}?>
<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="lesss.png"></a>Title
<?php if($_SESSION["toggle"] == 'show'){ ?>
<div id="contentDivImg" style="display: block;">
<?php
$_SESSION["toggle"] = 'hidden';
}
if($_SESSION["toggle"] == 'hidden'){ ?>
<div id="contentDivImg" style="display: none">
<?php $_SESSION["toggle"] = 'show';
} ?>
Try Show & hide
</div>
I second #Akam and #ChaseMoskal suggesting you use JavaScript for this.
It should be as simple as
<html>
<head>
<script type="text/javascript">
function toggle(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
// Also set the toggle cookie on toggle
document.cookie = 'toggle=hide'
ele.style.display = "none";
imageEle.innerHTML = '<img src="more.png"">';
}else {
// Also set the toggle cookie on toggle
document.cookie = 'toggle=show'
ele.style.display = "block";
imageEle.innerHTML = '<img src="less.png">';
}
}
</script>
</head>
<body>
<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="lesss.png"></a>Title
<div id="contentDivImg" style="display:block">Try Show & hide</div>
<script type="text/javascript">
// Run at the end of the body so that the dom is ready for us
// Dont beleave me? reade this: https://groups.google.com/forum/#!topic/closure-library-discuss/G-7Ltdavy0E
(function(){
// Get the cookie we want to check using a fancy-pants regex
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)toggle\s*\=\s*([^;]*).*$)|^.*$/, "$1");
if (cookie === 'hide')
// If the cookie says hide, just use the toggle function
// The user wont see the change because were still running way before readystate complete
toggle('contentDivImg', 'imageDivLink');
}())
</script>
</body>
</html>
This uses document.cookie to set a toggle cookie to either show or hide.
If the toggle cookie is hide then the toggle function gets called before the page finishes loading.
Note that while this will work when the file is served from a remote server (or localhost) over http(s), it won't work if the file is retrieved using the file: protocol because cookies are associated with a domain.
If you want to learn more about using cookies in JavaScript or just want to copy and past some useful functions (and even a small framework) check out the MDN article

Keeping variables from PHP while loop

I have been looking all over for a way to do this.
I use a PHP while loop to get some variables from a database:
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<script type="text/javascript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
//-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
<? } //end while
?>
Sometimes i get 10 results, and i make 10 Go! bottoms. But when i come to the delete page, the $is variable is off cause the same as the last result, no matter witch of the bottoms i press..
Any ideas on how to get around that, so i get the confirm box, and still keep the right id to be deleted?
You're creating a global function called "go_there" for each entry, so only the last one will remain. Instead of that, create just one function, and fetch the "id" value from an attribute on the button.
function go_there(button)
{
var id= button.getAttribute("data-id");
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
}
Then:
<INPUT TYPE="button" value="Go!" onClick="go_there(this)" data-id="<?php echo $id ?>">
It seems to me like you're creating your javascript function in your loop as well so it only fires one of them (you're creating multiple functions with the same name. How is it supposed to know which one to use). You should create 1 javascript function and pass the id into it as a a parameter
<script type="text/javascript">
function go_there(id)
{
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
</SCRIPT>
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
echo '<td><form><INPUT TYPE="button" value="Go!" onClick="go_there(<?php echo $id; ?>)"></form></td></tr>'
} //end while
?>
Overall this is a poor way to do this. You should avoid wrtiting handlers inline unless you have a specific case where it is the only way. Much better if you attach a handler to the elements in questions (working fiddle - for firefox anyhow...):
<!-- output our inputs with the id value in an attribute data-id-value -->
<?php while ($row = mysql_fetch_array($query)): $id = $row["ID"]; ?>
<td><form><INPUT class="go-button" TYPE="button" value="Go!" data-id-value="<?php echo $id ?>"></form></td></tr>
<?php endwhile; ?>
<script type="text/javascript">
var goButtons = document.querySelectorAll('input.go-button'), // select all out buttons
// define our handler function
goThere = function (event) {
// get the id the we encoded from php from our data attr
var id = event.target.getAttribute('data-id-value');
if(confirm('Are you sure you want to delete?')) {
// if confirm is true then redirect to the delete url
window.location = "index.php?p=delete&id=" + id;
}
};
// loop over the buttons and attach the handler
for (var i = 0; i < goButtons.length; i++) {
goButtons[i].addEventListener('click', goThere);
}
</script>
The issue here is that that isnt necessarily cross browser. Thats typically one of the reasons people use libraries like jQuery or similar so that they don't have to normalize dom querying and listener attachment.
Here is a corrected script.
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<SCRIPT language="JavaScript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to == true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
Your button will not work because you have added the comment markers <!-- and --> to the function. If you want help with that then please comment.
Also, can you clarify you're issue in the comments? We can help you better then.

Give PHP value into Javascript in same page

How can I give the ID value to Javascript in same page.
Example data :
<a href="" id="ctextarea<?php echo $uid; ?>"/>
JS :
function recountss()
{
var maxlen=280;
var current = maxlen-$('#ctextarea').val().length;
$('.counters').html(current);
if(current<0 || current==maxlen)
{
$('.counters').css('color','#D40D12');
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else if (!$.trim($("#ctextarea").val())) {
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else
$('input.comment_button').removeAttr('disabled').removeClass('inact');
if(current<10)
$('.counters').css('color','#D40D12');
else if(current<20)
$('.counters').css('color','#5C0002');
else
$('.counters').css('color','#C0C0C0');
}
I tried using get class, but it's effect for 1 data not for many data.
Have idea ?
Thanks.
This should work :
<script type="text/javascript">
var id = "ctextarea<?php echo $uid; ?>";
</script>
In your javascript, you can do :
var current = maxlen-$(id).val().length;
But you should use an other name for your variable.
Try data- attributes:
Link
In JS you can do the following:
document.getElementById('link').getAttribute('data-id');
This stuff is perfectly valid in HTML5 - but even older browsers just don't care.

How can I automatically show a jquery colorbox on my page when a certain $_GET variable is passed?

I have a jquery colorbox (lightbox) that pops up when users click a button on my page. Under certain conditions though i want this colorbox to appear without the user having to click a button. For example when the page is loaded and variable is passed in the query string I want to pop up the colorbox.
For example the following code shows how when user clicks the signup button the colorbox appears (this is for a page called example.php)
<p class="signup_button"><img src="images/buttons/sign_up_now.gif" alt="Sign Up Now"></p>
<script type="text/javascript">
$('.free_signup_link').colorbox({href:"signup.php?type=5"});
</script>
What I want to do is if the page is loaded with a variable in the query string then the colorbox is automatically shown (eg for example.php?show=1)
if($_GET['show'] == "1") {
// show the color box
}
Anyone know how to do this?
thanks
This should work, it's probably considered a bit "dirty" however.
<?php
if($_GET['show'] == "1") { ?>
<script type="text/javascript">
$.colorbox({href:"signup.php?type=5"});
</script>
<?php } ?>
Why not just use jQuery?
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var show = getUrlVars()["show"];
if(show == 1) {
$.colorbox({href:"signup.php?type=5"}).click();
}
Reference: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
How about this?
if($_GET['show'] == "1") {
echo '
<script type="text/javascript">
$.colorbox( ... ); // or whatever that triggers the colorbox
</script>
';
}

Categories