getting data attrib value from html to jquery - javascript

So I have a bunch of images for which I am adding a few data attributes, which I want to use later on in jquery.
The PHP/HTML looks kind of like this:
<?
foreach($images as $image)
{
?>
<div class='dyn-img'>
<img <!-- start image tag -->
src="<? echo $image['src']?>"
data-aspect-ratio ="<? echo $image['aspect_ratio']?>"
... //other dynamic data attribs
> <!-- end image tag -->
</div>
<?
}
?>
Later on in jQuery, I need to take these dynamically loaded images and pass their aspect ratios into a library function:
So in the jQuery part I do (inside document.ready fn):
$(".img-holder > img").cropper({
aspectRatio: 1, //<-- this needs to be the data-aspect-ratio defined earlier
... other attributes...
});
I tried using aspectRatio: this.data("aspect-ratio") however that gives me a javascript error saying
TypeError: this.data is not a function
aspectRatio: this.data("aspect-ratio"),
My jQuery skills are basic, so I am hoping there is some jQuery/Javascript masters here who can help show me how I can pass that value into this function.
Any help is greatly appreciated!

I would loop using each, get the attribute, then call cropper
$(".img-holder > img").each(function() {
var size = $(this).data("aspect-ratio");
$(this).cropper({
aspectRatio: size
});
});

Related

passing a PHP variable to Ajax call [duplicate]

This question already has answers here:
trimming a string within a div
(2 answers)
How can I get the data attribute from a php variable?
(2 answers)
Closed 2 years ago.
I am attempting to call a comments section through a modal, for this purpose I need to pass a unique id along with #display_comment . It works when I hard code is such as #display_comment1, #display_comment2. I need to know how to pass the value as a variable.
I am using dom-target to pass it as variable in myData1, but it wont work. The console shows #display_comment & 1 on the next line.
<div id="dom-target" style="display: none;">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
var div = document.getElementById("dom-target");
var myData1 = div.textContent;
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment'+myData1).html(data);
}
})
}
The DIV includes lots of whitespace around the ID. You need to remove that with trim().
var myData1 = div.textContent.trim();
What #barmar wrote is correct. Although I would suggest a much better approach for this. Whenever you wanna "fetch" some html data to javascript (here the data is set by PHP), you can use the data attribute in html like this:
<div id="dom-target" style="display: none;" data-id="<?php echo htmlspecialchars($test['id']);?>">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
See that I've set the data attribute to the div above with the id.
Now when you wanna get this id in jQuery, you can do it with $("#dom-target").data("id"); like
var myData1 = $("#dom-target").data("id");
This gives you a much better and cleaner way to fetch data from html to javascript.

Image url in css based on html title value

I'm trying to generate multiple hexagons with background images, using a php for loop:
<?php
$dir = 'resources/images/logos';
$images = scandir($dir);
for($i = 2; $i < count($images); $i++) {
$title = explode('.', $images[$i])[0];
?>
<div class="hexagon_loc<?= $i ?>">
<div class="hexagon image" title="<?= $title ?>"></div>
</div>
<?php } ?>
This works fine, I make a div, with a different class name every time and with the correct title (based of on the filename of the image). Now I want to have a for loop in scss which draws the hexagons, I also want to define the background-images there. But since I can't pass any kind of variables from html/php to css/sass and the fact that the attr() function is widely unsupported I have no way of dynamically doing this, which would result in the titles possibly being mismatched with the images. Is there anyway to do this anyways? Or do I have to use a different approach entirely?
Example sass where I want to define the image:
.hexagon_loc {
$image: '../../resources/images/bill.jpeg';
#include hexagon($image);
margin-left: 100px;
}
Using vanilla JavaScript to solve this would also be a possibility
Thanks
In this situation, I would use <img> HTML element.
There is a CSS solution but it is not supported in many browsers.
div { background-image : attr(data-image); }

jQuery add variable to selector not working

I am passing an ID to a selector, but somehow it doesn't work. When I hardcode it, then it works. Below is my script and the various ways I have tried. :
jQuery("li.<?php echo slugify($catId); ?>").closest("ul").closest("li").addClass("active");
When I view in console, the script above echoes out the $catId correctly but it just doesn't work.
Then I tried this :-
var catId='<?php echo $catId; ?>';
jQuery("li."+catId).closest("ul").closest("li").addClass("active");
In the console, the variable catId wasn't printed out at all. It shows ("li."+catId) in the console.
Then I tried converting it to string and pass it to the selector like this :
var catString = catId.toString();
It doesn't work either. I hardcode the catId directly to the line and it works just fine.
Anyone can help? Thanks in advance.
If you are trying the above snippets your HTML should look like this
<li class="<?php echo slugify($catId); ?>"> ....
And you shouldn't be associating them to id attribute
I have managed to solve it!!!
It's just moving the whole <script></script> to after the <li> </li>
Basically the placement of the script causes the issue. :)

How do I get justifiedGallery plugin to work with multiple galleries?

I am using this wonderful jquery plugin called justified gallery. Below is a simplified html syntax to use this plugin, followed by javascript syntax.
HTML
<div id="my-gallery">
<a href="path/to...............">
<img src="path/to/............1.jpg" />
</a>
<a href="path/to...............">
<img src="path/to/............2.jpg" />
</a>
.......
</div>
JAVASCRIPT
<script>jQuery("#my-gallery").justifiedGallery({
rowHeight : 120,
margins : 0
});</script>
ISSUE - With the above code the plugin is working just fine BUT only for the first instance of the html syntax. Meaning, if I try <div id="my-gallery">......</div> twice or more on the same page, it only works on the first instance. Since there is going to be multiple galleries on a same page I need this to loop.
I can handle php well but yet to start learning javascript so unable to hack the javascript. If it was only php I would have generated different ids for each gallery with something like the code below.
$arr = array('first_gallery', 'second_gallery', 'third_gallery');
$i = 0;
foreach($arr as $a){
echo '<div id="my-gallery-'.$i.'">'.$a. '</div><br>';
$i++;
}
The code above would have resulted to this in the view-source.
<div id="my-gallery-0">first_gallery</div><br>
<div id="my-gallery-1">second_gallery</div><br>
<div id="my-gallery-2">third_gallery</div><br>
So the question is, is my logic correct to solve this, if yes then (since my javascript is nill) how do I solve this in context of my javascript. Any response if appreciated. TIA.
You are not allowed to have multiple element with identical id's... so having two or more <div id="my-gallery"> is invalid HTML.
Instead give each one a class, and use that class name as the selector in your jQuery.
<div id="my-gallery1" class="my-gallery-class">
...
</div>
<div id="my-gallery2" class="my-gallery-class">
...
</div>
$(function(){
$(".my-gallery-class").each(function(){
$(this).justifiedGallery({
rowHeight : 120,
margins : 0
});
});
});
Use a class instead. An ID must be unique. Having multiple identical IDs is invalid HTML. Output as follows:
$arr = array('first_gallery', 'second_gallery', 'third_gallery');
foreach($arr as $a){
echo '<div class="my-gallery">'.$a. '</div><br>';
}
And use Javascript then like this. (Note that a document ready event might be required!)
<script>
$(document).ready(function() {
$(".my-gallery").justifiedGallery({
rowHeight : 120,
margins : 0
});
</script>
Using br in HTML for this purpose is discouraged. If your elements are block elements and are not floated or absolutely positioned, you won't need br. If you want some space between them you can set a margin is CSS (and remove br):
.my-gallery {margin: 24px auto;}
If you want to keep the unique ID on the gallery items (I don't know why, it seems pointless and needless markup to me, but anyway) you can do it like this:
$arr = array('first_gallery', 'second_gallery', 'third_gallery');
$i = 0;
foreach($arr as $a){
echo '<div class="my-gallery" id="my-gallery-'.$i.'">'.$a. '</div><br>';
$i++;
}
As others have suggested you can give each gallery a common class and use that in your JavaScript
eg:
<div class="gallery" id="my-gallery-0">first_gallery</div><br>
<div class="gallery" id="my-gallery-1">second_gallery</div><br>
<div class="gallery" id="my-gallery-2">third_gallery</div><br>
<script>
jQuery(".gallery").justifiedGallery({
rowHeight : 120,
margins : 0
});
</script>

Javascript & JQuery Troubles - Grabbing & Writing YouTube Data to Page

I would say I have a little experience with Javascript and JQuery, but in the time spent working on one of my newer sites, nothing is going my way. Basically, I use PHP to write a video ID to javascript code, which then executes to get a YouTube video's title, uploader, views, and length. Everything is working fine on my other site ('Latest Videos' sidebar on Mechabyte.com) but on my newer one, FirstPersonTheater.net, nothing works. I've included the JQuery library, but my scripts aren't writing the information to each post's div fields. I've rationalized that this could simply be an effect of using a barebones theme (I'm building my own, but want to get the kinks worked out as I build it), but since I have all the requirements (JQuery library in header + scripts) I think it should still work. Here's a peek at my source code, you can also visit the site and inspect some of the elements to see if I'm missing anything.
Basic layout (Assume video ID is 0000000000000:
<div class="index_post">
<a href="<?php the_permalink() ?>">
<div class="image">
<div class="container" style="background:url('http://img.youtube.com/vi/0000000000000/0.jpg');">
</div>
<div id="data_time<?php the_ID(); ?>" style="position:absolute;z-index:9;text-decoration:none;bottom:2px;right:2px;font-size:10px;color:#fff;background:#000;padding:0px 2px;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;opacity:0.75;">
3RR:0R!
</div>
</div>
<div class="postinfo">
<div class="data_uploadedby<?php the_ID() ?>"></div>
<div class="data_views<?php the_ID() ?>"></div>
</div>
<div class="extras">
<script type="text/javascript">
function ytindex<?php the_ID(); echo time() ?>( data )
{
$('#data_time <?php the_ID() ?>').html( secondsToHms( data.entry[ "media$group" ][ "yt$duration" ].seconds ) );
$('.data_postedby<?php the_ID() ?>').html( 'by ' + data.entry[ "author" ][ 0 ].name.$t );
$('.data_uploadedby<?php the_ID() ?>').html( data.entry[ "title" ].$t );
$('.data_views<?php the_ID() ?>').html( data.entry[ "yt$statistics" ].viewCount + ' views</h3>' );
}
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/0000000000000?v=2&callback=ytindex<?php the_ID(); echo time() ?>"></script>
</div>
</a>
</div>
Here's the result (CSS elements like thumbnail display fine, because they're handled w/ PHP, none of the other elements load): http://i.stack.imgur.com/0HYKQ.png (link b/c of SO rep)
Thanks in advance! From experience I can say most of the people on this site are awesome helpers! -Matt
the jquery library is already included in the current versions of wordpress. Use wp_enqueue_script to add the jquery library.
Don't just add the script to your header.php file...
Then you'll also need to use this ready function for compatibility with wordpress.
jQuery(document).ready(function($){
// now you can use jQuery code here with normal $ shortcut formatting
});

Categories