javascript display and hide div element - javascript

I am new to Javascript, and I currently have an article that is being fetched from database, the article has two rows. title & content there are about 100 of these in my database. Now the objective is to list all the titles first, and when a user clicks on a title, to make the the relevant content appear underneath it. I can do this however this way.
<?php
//mysql query here...
foreach($result as $row) { ?>
<div id='title'> <?= $row['title'] ?> </div>
<div id='<?= $row['id'] ?>' style='display:none'
onclick=showContent(<?= $row['id'] ?>) > <?= $row['content'] ?>
</div>
<?php } ?>
The javascript to hide the show the content is this:
<script type='text/javascript'>
function showContent(id){
document.getElementById(id).style.display='inline';
}
</script>
The showContent() function hides the div based on the id passed through the paramenter.
But, the only problem is that, I need other previously displayed divs to truntate when a new one opens.
Meaning, the content should be visible only once, then when you click on another title, the previously opened content should disappear and only the new content should appear.
I hope that made sense. as I am lacking the grammar to explain it all. I tried to give small example here, which for some reason does not seem to work at all, but does in my localhost http://jsfiddle.net/YL6aH/
EDITED:
My full PHP loop, together will all the js/html
<?php
$articlesForPreview = $createQuery
->query("SELECT * FROM timeline");
$fetchAll = $articlesForPreview->fetchAll(PDO::FETCH_ASSOC);
foreach($fetchAll as $row) {?>
<div id='timeline_container'>
<span class='timeline_date'> <?= $row['time'] ?></span>
<span class='timeline_title'> <a href='#' onclick=timeline(<?= $row['id'] ?>)><?= $row['title'] ?></a></span>
<p id='<?= $row['id'] ?>' style='display:none;'> <?= $row['event'] ?></a></span>
</div>
<?php }?>
</aside>
</section>
<script type='text/javascript'>
function timeline(id){
document.getElementById(id).style.display='inline';
}
</script>
<footer id='footer_container'>

You can simply remember the last item that is visible:
var active;
function showContent(id){
if (active) active.style.display = 'none'; // hide previously visible element
active = document.getElementById(id); // keep track of the element you are about to show
active.style.display='inline'; // show the new element
}
Keep in mind that this solution starts with no items visible and after that only allows one item to be visible at a time.

You should try this :
function showContent(id){
$('.active').hide().removeClass('active');
$('#'+id).show().addClass('active');
}
I see also that you will have multiple elements with id=title, you must change it to make every elem unique.

You can go through all elements with an onclick of "showContent", hide them all, afterwards you can just show the one you want.
function showContent(id){
var allElements = document.getElementsByTagName('*');
for ( var i = 0; i<allElements.length; i++ ) {
if ( (allElements[i].onclick + "").indexOf("showContent") >= 0) {
allElements[i].style.display = "none";
}
}
document.getElementById(id).style.display='inline';
}

I'm pretty new to javascript and jquery myself, but one of the things we just did in the class I'm taking was the accordion display, where you attach event handlers in the document.ready for the click events for the header objects, and their div children elements, and it was done by swapping the css classes on the click events... are you using css? in our version, anytime we clicked on a plus, it would expand the display to display the divs below, and clicking the minus pic it would close them... ours did it for all of them, but you should be able to code that even to "close" all of those displays, and then open/display only the divs that are children for the item clicked... is that what you're looking for?

Related

Use PHP in a Shortcode to pull content from specific post ID

I am trying to create a shortcode that references content from a specific post ID. I have the code referenced below. It's set up so that if someone clicks the button, it will reveal content from the popup-id that will be defined in the shortcode. The popup-id is linked to a specific page/post.
function subscribe_link_att($atts, $content = null) {
$default = array(
'link' => '#',
'popup-id' => '4582'
);
$a = shortcode_atts($default, $atts);
$content = do_shortcode($content);
return '<button class="popup_button"> <span class="text">'.$content.'</span></button>
<div id="'.($a['popup-id']).'" style="display: none" class="hide">
<div class="social-popup-inner">
<img id="social-popup-close" src="/wp-content/themes/huh/_static/images/close-button.svg" alt="close">
<?php
$popup = get_post('.($a['popup-id']).');
echo $popup->post_content;
?>
</div>
</div>
';
}
add_shortcode('subscribe', 'subscribe_link_att');
The issue is that when I click the button, the content isn't pulling through (it just saying post_content; ?>).
It looks like the PHP code is being commented out (screenshot hyperlinked here)
I would love any feedback or direction.
I have a sample page here that I am playing with . It's formatted poorly but it's just for me to test things out in. The button called "TEXT HERE" is the button I am working on.
https://heyuhuman.com/melissa-test/
THANK YOU SO MUCH

Get array number by position

Array in php each record goes inside a hidden div
$array=(15,20,50,23,10);
record list (loop)
<div>15</div> position 1
<div>20</div> position 2
<div>50</div> position 3
<div>23</div> position 4
<div>10</div> position 5
The code is
for($i=0;$i<count($array);$i++) {
<input id="postid" name="postid" type="hidden" value="$array[$i]; ?>"
}
If I click div post id (position 2) I get 20 if I click div post id position 3 I get 50
(function ($){
$(document).on('click','#postid',function(e){
e.preventDefault();
var postid=$('#postid').val();
console.log(postid);
});
})(jQuery);
So you need to echo the input tag along with the Position text. Also, it is a good practice to wrap the text node inside a parent tag for referring, like a div. id needs to be unique for each HTML element. In your case, having an id or class attribute is trivial anyways since the input type is hidden.
So, better to add a class for the parent div tag and output the text on it's click listener.
Backend Snippet:
<?php
$array = array(15,20,50,23,10);
for($i = 0; $i < count($array); $i++) {
echo "<div class='post'><input name='postid_$array[$i]' type='hidden' value='$array[$i]' /> Position ".($i + 1)."</div>";
}
Frontend Snippet:
(function ($){
$(document).on('click','.post',function(e){
console.log($(this).text());
});
})(jQuery);
Online Output UI demo
This should work for you.
PHP snippet
$array = array(15,20,50,23,10);
$i = 1;
foreach($array as $single_value) {
echo "<div class='post'><input name='postid_".$i."' type='hidden' value='".$single_value."' /> Position ".$i."</div>";
$i++;
}
Front-end Javascript
(function ($){
$(document).on('click','.post',function(e){
console.log($(this).find('input').val());
});
})(jQuery);

selecting parent() becomes different in what is supposed to be the same link <a>

So here is my problem:
I want to select the div with the class "read_more hidden".In the first link it selects it, but on the second one it doesn't.It says undefined..Could someone explain to me what's going on?
(I am trying to make "read more.." link on a big text coming from the database)
PHP
while($row=mysql_fetch_assoc($result))
{
$str==NULL;
$offset==NULL;
$max_length==NULL;
$str=$row['subject'];
$max_length = 3500;
if (strlen($str) > $max_length)
{
$offset = ($max_length - 3) - strlen($str);
$str = substr($str, 0, strrpos($str, ' ', $offset)) . '<br></br><a class="clicky" href="">read more...</a>';
}
echo'<div class="GTextBorder" >
<center>
<h3>
<em>';
if ($row['title']==NULL)
{
echo 'No title';
}
else
{
echo ''.$row['title'].'';
}
echo '</em></h3></center><br></br>
<div class="read_more hidden" >'.$row['subject'].'
<a class="clickya" href=""><i>less...</i></a>
</div>
<div class="item" >'.$str.'</div>
<br></br>';
echo '</div>';
echo '<br></br>';
}
JS
$('.clicky').click(function(e){
e.preventDefault();
var id=$(this).parent().parent().prev().attr("class");
window.alert(id);
});
Some explanation:
I first take the $row['subject'] which is the longtext and i check if it's more than 3500 chars.if it is then i put read more.. link so it can open.My first idea was to make two separate divs(one hidden) one normal so when read more.. is clicked the two divs would change.so read_more div would be shown and ".item" div would be hidden.But for some reason when the third long text is printed with read more.. link it just cant select the whole GTextBorder div. i don't know why.

Apply the right content to a modal with jQuery and the right button id's

So lets be straight to the point;
I am using a WP theme and obviously it has some widgets in it.
Now I want to add 1 button to each widget.
Var instance would be the widgets so I only add buttons aslong as there are widgets.
The a tag is designed to be a button.
<?php
$i = 0;
while($i <= count($instance)) {
$id = $i
}
echo "<a id='stats".$id."' data-toggle='modal' data-target='#Modal' class='btn btn-primary custom-button oceanblue-btn'>Link</a>";
?>
For each(?) button the id should +1, so
Widget 1 would contain a button with ID="stats0", Widget 2 would have a button with ID="stats1" and so on.
This way I can get the element trough jQuery and show the modal with the right content, correct?
But the question itself; How can I get the id to increase by 1 when I have to set the buttons outside of the loop?
UPDATE
As Trincot mentioned, it isn't really clear what the thing is that I want to accomplish.
You can check out the live version which is here.
If you scroll down to the second section, you'll see 6 circle which contains an image and text. The maker of the theme calls these things instances within the code;
function widget($args, $instance)
{
extract($args);
echo $before_widget;
?>
<div class="col-lg-3 col-sm-3 focus-box" data-scrollreveal="enter left after 0.15s over 1s">
<?php if( !empty($instance['image_uri']) ): ?>
<div class="service-icon">
<?php if( !empty($instance['link']) ): ?>
<i class="pixeden" style="background:url(<?php echo esc_url($instance['image_uri']); ?>) no-repeat center;width:100%; height:100%;"></i> <!-- FOCUS ICON-->
<?php else: ?>
<i class="pixeden" style="background:url(<?php echo esc_url($instance['image_uri']); ?>) no-repeat center;width:100%; height:100%;"></i> <!-- FOCUS ICON-->
<?php endif; ?>
</div>
<?php endif; ?>
<h5 class="red-border-bottom"><?php if( !empty($instance['title']) ): echo apply_filters('widget_title', $instance['title']); endif; ?></h5>
<!-- FOCUS HEADING -->
<?php
if( !empty($instance['text']) ):
echo '<p>';
echo htmlspecialchars_decode(apply_filters('widget_title', $instance['text']));
echo '</p>';
endif;
?>
<?php
for($i =0; $i <= count($instance); $i++) {
echo "<a id='stats$i' data-toggle='modal' data-target='#Modal' class='btn btn-primary custom-button oceanblue-btn'>Link</a>";
}
?>
</div>
<?php
echo $after_widget;
}
Inside this function the elements get rendered one by one, if I'm right?
So what I wanted to do is apply a button to each element. When the ID's are set I have something to refer to within my jQuery to define the content of the model.
This is code which execute the rendering of the elements
<div class="row focus-section">
<?php
if ( is_active_sidebar( 'sidebar-ourfocus' ) ) :
dynamic_sidebar( 'sidebar-ourfocus' );
else:
the_widget( 'zerif_ourfocus','title=PARALLAX EFFECT&text=Create memorable pages with smooth parallax effects that everyone loves. Also, use our lightweight content slider offering you smooth and great-looking animations.&link=#&image_uri='.get_stylesheet_directory_uri()."/images/parallax.png", array('before_widget' => '', 'after_widget' => '') );
the_widget( 'zerif_ourfocus','title=WOOCOMMERCE&text=Build a front page for your WooCommerce store in a matter of minutes. The neat and clean presentation will help your sales and make your store accessible to everyone.&link=#&image_uri='.get_stylesheet_directory_uri()."/images/woo.png", array('before_widget' => '', 'after_widget' => '') );
the_widget( 'zerif_ourfocus','title=CUSTOM CONTENT BLOCKS&text=Showcase your team, products, clients, about info, testimonials, latest posts from the blog, contact form, additional calls to action. Everything translation ready.&link=#&image_uri='.get_stylesheet_directory_uri()."/images/ccc.png", array('before_widget' => '', 'after_widget' => '') );
the_widget( 'zerif_ourfocus','title=GO PRO FOR MORE FEATURES&text=Get new content blocks: pricing table, Google Maps, and more. Change the sections order, display each block exactly where you need it, customize the blocks with whatever colors you wish.&link=#&image_uri='.get_stylesheet_directory_uri()."/images/ti-logo.png", array('before_widget' => '', 'after_widget' => '') );
endif;
?>
</div>
Now you probably will need to know what 'dynamic_sidebar' is.. but untill now I haven't found that piece yet
You should generate the buttons inside the loop, and you don't need two variables when the only thing you do is make them equal. And such loops are best written with a for loop:
for($i =0; $i <= count($instance); $i++) {
echo "<a id='stats$i' data-toggle='modal' data-target='#Modal'
class='btn btn-primary custom-button oceanblue-btn'>Link</a>";
}
Note also you had a missing ending quote for the id attribute, and that you can embed variables without interrupting the quoted string.
jQuery Solution
You could also decide to leave the php code alone, and just manipulate the document with jQuery. For starters, you could add an id attribute to each of the instances, which have a class pixeden. And then you could capture click events on these, to perform any further action:
jQuery(function($) {
// Add an id attribute to the instances:
$(".pixeden").each(function(idx) {
$(this).attr('id', 'instance' + idx);
})
// Capture click event on any of the instances:
$(".pixeden").click(function () {
console.log('you clicked instance with id=', this.id);
// any other action follows here...
});
}, jQuery);

PHP: print from a list of data (loop difficult)

Hi i have a little problem,my code create a list of buttons and each button have a name(value) from my list (table 'usernames')
....for exemple (table 'usernames' have 3 lines aa-bb-cc my code make 3 button with values aa & bb & cc..............
so what i want to do, is when i click on a button i want to print the value of this button in a div, for exemple if i click on the button who have the value 2 i want to print 2 in the div(i have a problem whit my loop, and i need help please)
this is my code:
$conn=mysqli_connect("localhost", "root", "pwd","sn") or die(mysqli_error());
$que2=mysqli_query($conn,"select usernames from posts", MYSQLI_USE_RESULT); // return a lot of lines on 'usernames'
$re=0;
$datax=array();
$i=0;
while ($r = mysqli_fetch_array($que2))
{
$re = $r["cnt"];
$datax[$i]=$re;
?>
<input id="ppost" name="ppost" value="<?php echo $datax[$i]; ?>" type="submit">
<br>
<script type="text/javascript">
$(function(){
$('#ppost').click(function(){
alert("<?php echo $datax[$i]; ?>");
});
});
</script>
<?php
$i++;
}
Ok, so there're few things to have a look at:
take the <script> out of the loop - one script can take care of all the buttons
you can't give same ID to all your inputs - id="..." has to be unique throughout your script
the JS script (assuming you have jQuery included prior to your ) should be:
<script type="text/javascript">
$(function(){
$('input[type="submit"]').click(function(){
alert($(this).attr('value'));
});
});
</script>
this should do the trick, let me know if this is what you wanted.

Categories

Resources