Add Class to Object on Page Load or on Click - javascript

This is my Current Code in my wordpress:
<div class="entry-content">
<a href="<?php
echo $currenturl.'?material=&type='.$get_type;
?>">All Materials</a>
<?php
$materials = get_field('materials',$valueid);
foreach($materials as $id):?>
<a href="<?php
$matterm = get_term($id,'materials');
$matslug = $matterm->slug;
$mattitle = $matterm->name;
echo $currenturl."?material=".$matslug.'&type='.$get_type;
?>"><?php
echo $mattitle;
?>
</a>
<?php endforeach; ?>
</div>
This is the Current Output:
<div class="entry-content">
<a href="#>Material 1</a>
<a href="#>Material 1</a>
</div>
And I want the output of the code will be:
<div class="entry-content">
<a class="current" href="#>Material 1</a>
<a href="#>Material 1</a>
</div>
and I have this Script on my header but it will not function:
<script type="text/javascript">
window.onload = function() {
document.getElementById('entry').className = 'current';
};
</script>

You're mixing up class and id (or just left off the id). If you do console.log(getElementById("entry")), I bet you get back null.

I think you have to replace this.
window.onload = function() {
var parentDiv = document.getElementsByClassName('entry-content');
parentDiv.childNodes[0].className = 'current';
};

In your code:
document.getElementById('entry').className = 'current';
getElementById(ID) it's a javascript method and used for getting the element with the specific ID
And your HTML is not correct, you forgot the end " of href.
You should write your HTML like -
<div class="entry-content">
<a id="entry" href="#">Material 1</a>
Material 1
</div>
After make above changes, your code works perfectly. See Demo

Related

PHP read more read less - Magento 2

I made an read more read less script for my Magento 2 webshop. This is used on a category page where there are serval subcategorie blocks to choose, each subcategory has a description with.
The problem: if I click read more all the descriptions of the subcategories will expand in stead of only the description of the subcategory I clicked read moreI am starting to learn PHP and Magento 2 but I can't fix this, does someone know the solution?
<div class="product description product-item-description">
<div class="more">
<?php if ($_subCategory->getDescription()) {
$string = strip_tags($_subCategory->getDescription());
if (strlen($string) > 250) {
// truncate string
$stringCut = substr($string, 0, 250);
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... Lees meer';
}
echo $string;
?>
</div>
<?php
}else {?>
<?php /* #escapeNotVerified */ echo $_attributeValue;
}
?>
</div>
<div class="less" style="display:none">
<?php echo $_subCategory->getDescription(); ?>
Lees minder
</div>
<script type="text/javascript">
console.log('test');
require(["jquery"],function($){
$('.readmore').on("click",function(){
$('.less').show();
$('.more').hide();
});
$('.readless').on("click",function(){
$('.less').hide();
$('.more').show();
});
});
</script>
</div>
This is because, when you type $('.less').hide(); this is grabbing every element with the attribute class='less'. This is the way I would overcome this:
Start by attaching a unique attribute to each <div class="more"> or <div class="less"> - in this case, we use the class attribute: (and move 'more' or 'less' to an id)
<div id="read-more-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read more" content -->
<a class="link" href="#read-more-block">Read Less</a>
</div>
<div id="read-less-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read less" content -->
<a class="link" href="#read-less-block">Read More</a>
</div>
We now have a read-more-block and a read-less-block for each subcategory. When we click the inside link a jQuery event should fire which will hide itself and display the other.
And then, in your jQuery:
$('#read-more-block .link').on('click', function() {
var $readLessBlock = $('#read-less-block.' + $(this).parent().attr('class'));
$readLessBlock.show(); //Show the read less block
$(this).parent().hide(); //Hide the read more block
});
..and vice versa for read less.

facebook share on page load using javascript

When using below code share on Facebook but https://www.facebook.com/dialog/return/close#_=_ does nothing return.
<?php
$social_link = "https://www.google.co.in";
$sharelink = "http://www.facebook.com/sharer.php?u=".urlencode($social_link)."&t=&s=100";
$strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
echo "<script>var win = window.open('$sharelink', '_self', '$strWindowFeatures');</script>";
?>
You can create share button using the given tag and add given script in your script section
<a onclick="shareinsocialmedia('https://www.facebook.com/sharer/sharer.php?u=<?php echo $ShareUrl;?>&title=<?php echo $Title;?>')" href=""> <img src="images/facebook.gif" title="share in facebook"> </a>
<script type="text/javascript" async >
function shareinsocialmedia(url){
window.open(url,'sharein','toolbar=0,status=0,width=648,height=395');
return true;
}
</script>

How to pass data of a JavaScript variable to another php page?

I have two pages: test.php and backend.php.
test.php has three images which when clicked takes the user to backend.php. I want the src of the image clicked to be displayed on backend.php. I am trying to achieve this task via JavaScript and Ajax but the src of the image doesn't appear on backend.php. Code for the same are given below:
test.php:
<?php
session_start();
?>
<html>
<head>
<script src="jquery-1.9.1.js">
</script>
<script>
function clickIt(data){
$.ajax({
url: 'backend.php',
data: {"imgsrc":data},
type: 'post',
success:function(res){
alert(res.message);
}
});
}
</script>
</head>
<body>
<a href="backend.php">
<img onclick="clickIt(this.src)" src="img1.jpg"/>
</a>
<a href="backend.php">
<img onclick="changeIt(this.src)" src="img2.jpg"/>
</a>
<a href="backend.php">
<img onclick="changeIt(this.src)" src="img3.jpg"/>
</a>
</body>
</html>
backend.php:
<?php
session_start();
?>
<?php
echo $_POST['imgsrc'];
echo 'Back';
?>
What am I possibly doing wrong?
Try this;
HTML:
<body>
<a href="javascript:void(0);">
<img onclick="clickIt(this.src)" src="img1.jpg"/>
</a>
<a href="javascript:void(0);">
<img onclick="changeIt(this.src)" src="img2.jpg"/>
</a>
<a href="javascript:void(0);">
<img onclick="changeIt(this.src)" src="img3.jpg"/>
</a>
</body>
Jquery:
function clickIt(data){
window.location.href = 'backend.php?imgsrc='+data; // redirect to backend.php
}
In backend.php
<?php
echo $_GET['imgsrc']; // use $_GET
echo 'Back';
?>
Click event of tag is not firing because tag takes the
page to backend page before tag click event gets fired. You can resolve this problem simply by removing the tag from each line.
You cannot access ajax response as res.message as you haven't echo the response in json format. You can access response simply from res variable
Also change the function name to changeIt to clickIt as you have defined function has clickIt
// use only res
success:function(res)
{
alert(res);
}
<img onclick="clickIt(this.src)" src="img1.jpg"/>
<img onclick="clikcIt(this.src)" src="img2.jpg"/>
<img onclick="clickIt(this.src)" src="img3.jpg"/>

Incrementing +1 the class in javascript

Hi im doing a PHP loop where I set a class, this loop make a list of items, and each one of them will have a "share" button that will open a window, (div display:none) the javascript open this div, and it works perfect..
My problem is that in this moment I have inserted the <script> code inside the loop so each item has its own <script></script> code...
Is there any way to do just one and take that code out of the php loop, so I can improve the code.
<script>
$('a.sharebtnc').click(
function(event) {
event.stopPropagation();
$('div.redescompartir').fadeToggle(300);
}
);
</script>
In the Loop well I just add to the class the id like this (id :32 )
<script>
$('a.sharebtnc32').click(
function(event) {
event.stopPropagation();
$('div.redescompartir32').fadeToggle(300);
}
);
</script>
How can I make this script works for all elements no matter the id number, I have no idea, but I know this is the correct way of doing this , right?
The HTML is very simple, its the same for each item... I mean each item has its own div with for <a href="" > </a> elements
<a href="#" class="sharebtnc(id)">
<div class="redescompartir(id)">
<a href="" >Twitter </a>
<a href="" >Facebook </a>
<a href="" >Google </a>
<a href="" >Foursquare </a>
</div>
Add a new class and attribute to the input element like
instead of
<a class="sharebtnc32" />
use
<a class="sharebtnc sharebtnc32" data-id="32"/>
then
jQuery(function ($) {
$('.sharebtnctl').click(function (event) {
event.stopPropagation();
$('.redesopenclose' + $(this).data('id')).fadeToggle(300);
});
})
My preferred method: PHP to generate link between the two elements, then a small snippet of JS to grab which particular one was clicked.
PHP:
$num = 100;
for ($x = 0; $x < $numItems; $x++) {
echo "
<a href='#' class='sharebtn' target='$x'>Share</a>
<div class='redescompartir' id='$x'>
<a href=''>Twitter</a>
<a href=''>Facebook</a>
<a href=''>Google</a>
<a href=''>Foursquare</a>
</div>
";
}
HTML output:
<a href="#" class="sharebtn" target='32'>Share</a>
<div class="redescompartir" id='32'>
<a href="" >Twitter </a>
<a href="" >Facebook </a>
<a href="" >Google </a>
<a href="" >Foursquare </a>
</div>
JS:
$('a.sharebtn').on('click', function(e) {
e.stopPropagation();
var target = $(e.currentTarget).attr('target');
$('#'+target).fadeToggle(300);
});
This way you only need a single <script></script> tag, which your user's broswers will thank you for. :)

Need help making jQuery loop for basic .fadeIn()/.fadeOut() slider

I'm new to jQuery and am having trouble figuring out the right way to loop a set of code for a basic carousel/banner rotator. I've tried a few versions of "for" statements and .each(), but I can't get it to work on my own so I'm reaching out for help.
Here's my code so far:
$('.next-1').click(function () {
$('.featured-1').fadeOut(500,function(){
$('.featured-2').fadeIn(500,function(){
$('.featured-2').toggleClass("hide");
});
});
});
$('.next-2').click(function () {
$('.featured-2').fadeOut(500,function(){
$('.featured-3').fadeIn(500,function(){
$('.featured-3').toggleClass("hide");
});
});
});
And then a similar code block for going back within the slider:
$('.prev-2').click(function () {
$('.featured-2').fadeOut(500,function(){
$('.featured-1').fadeIn(500,function(){
$('.featured-2').toggleClass("hide");
});
});
});
$('.prev-3').click(function () {
$('.featured-3').fadeOut(500,function(){
$('.featured-2').fadeIn(500,function(){
$('.featured-3').toggleClass("hide");
});
});
});
This code does work right now, I just don't want to have to output so many unnecessary lines of code when I know I could loop it. I'd like to be able to loop until there are no more "featured-n" divs to cycle through (being able to cycle around to the beginning would be great too!)
Here's the PHP/HTML I'm using to generate each "featured-n" div block:
function home_slider_loop() {
$count = 0;
query_posts ('tag=slider');
if (have_posts()) : while (have_posts()) : the_post();
$count++;
?>
<div class="featured-post featured-<?php echo $count; if ($count>1) { echo ' hide';}?>">
<div class="featured-header">
<h1 class="featured-title"><?php the_title(); ?></h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<?php the_post_thumbnail('full', array('class' => 'slider-image')); ?>
<div class="slider-nav">
<div class="featured-prev prev-<?php echo $count; ?>"></div>
<div class="featured-next next-<?php echo $count; ?>"></div>
</div><!--End Navigation-->
</div><!--End Image <?php echo $count; ?>-->
<div class="featured-footer">
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" >Read more</a>
</div>
</div><!--End Featured <?php echo $count; ?>-->
<?php
endwhile;
endif;
}
Here's a sample of one of the static HTML outputs (just imagine this iterated several times with the "featured-n" classes incrementing:
<div class="featured-1">
<div class="featured-header">
<h1 class="featured-title">5 Useful Cinematography Apps for iOS You Should Download Today</h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<img width="1018" height="416" src="http://www.tbabdev.com/wp-content/uploads/2013/07/cinematography-apps-8-hero.jpg" class="slider-image wp-post-image" alt="cinematography-apps-8-hero" />
<div class="slider-nav">
<div class="featured-prev prev-1"></div>
<div class="featured-next next-1"></div>
</div><!--End Navigation-->
</div><!--End Image 1-->
<div class="featured-footer">
<p>The devices we have in our pockets, the ones that can run these apps, these are the new leathermans. They have everything we need. They eliminate the need to carry paper manuals and enable us to do complex timelapse calculations in a fraction of the time as a paper and pen.</p>
<a class="more-link" href="http://www.tbabdev.com/?p=27" alt="5 Useful Cinematography Apps for iOS You Should Download Today" >Read more</a>
</div>
</div><!--End Featured 1-->
You can see the code in action at http://www.tbabdev.com/
Thank you in advance for your help and please be kind to a n00b :)
Use something like this :
$('.nav .prev').click(function(){
activeBlock = $('.featured.active');
prevBlock = activeBlock.prev('.featured');
activeBlock.fadeOut('slow',function(){
prevBlock.fadeIn().addClass('active');
}).removeClass('active');
});
$('.nav .next').click(function(){
activeBlock = $('.featured.active');
nextBlock = activeBlock.next('.featured');
activeBlock.fadeOut('slow',function(){
nextBlock.fadeIn().addClass('active');
}).removeClass('active');
});
Html
<div class="nav">
<div class="prev"> </div>
<div class="next"> </div>
</div>
<div class="featured-post featured <?php if($count>1) echo 'hide' ?>">
<div class="featured-header">
<h1 class="featured-title"><?php the_title(); ?></h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<?php the_post_thumbnail('full', array('class' => 'slider-image')); ?>
</div>
<!--End Image <?php echo $count; ?>-->
<div class="featured-footer">
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" >Read more</a>
</div>
</div>
You could do it this way :
$('.featured-next, .featured-prev').click(function () {
//find out if the clicked element is a prev or next element, extract the last part, will be useful later
var direction = $(this).hasClass("featured-next") ? "next" : "prev";
//select the ".featured-n" block which is the super-parent of clicked element
var $fullBlock = $(this).closest('div[class^="featured-"]'); //or add a class here to make your life easier
//fade out full block
$fullBlock.fadeOut(500, function () {
//search for the next element and show it
//note that $fullBlock.next() => $fullBlock["next"]() => $fullBlock[direction]()
$fullBlock[direction]().fadeIn(500, function () {
//toggle the class "hide" of the element next to fullBlock
$(this).toggleClass("hide");
});
});
});
Explanation:
You can join up both prev and next events together.
Then, you have to check if its a next or a prev element. Set that to a variable called direction. We'll be using this to find out if we have to use prev() or next() when we're trying to fadeIn featured-n divs.
Find the parent with the class set to featured-n (in your case its the superparent). It might be better if you give a common class to all these elements so that we can stop using 'div[class^="featured-"]' selector, which is slightly inefficient.
Fade out the superparent.
In the callback, based on the direction variable, we'll have to decide if the carousel is gonna go to prev block or next block, something like this :
if(direction === "prev")
{
$fullBlock.prev().fadeIn(//your code)
}
else
{
$fullBlock.next().fadeIn(//your code)
}
You must also know that, in an object like this :
var data = {"name" : "Blah Blah"}
To get the "Blah Blah" out, we can say
data.name
or we could say :
data["name"]
So based on this, in our situation, instead of
$fullBlock.prev()
Or we could say
$fullBlock["prev"]()
Which is what direction variable contains. So finally, we could do this to select the next/prev element based on what was clicked :
$fullBlockdirection
Show the prev/next element.
Add/remove "hide" class.
Hope this helped!

Categories