I have a series of <div>s each with an id of a color name e.g <div id="white"></div> that loads an audio file and fills a couple heading tags with the artist and track title gathered from an ajax call when the div is clicked
HTML
<audio id="song" preload="none">
</audio>
<div id="white"></div>
<div id="pink"></div>
<div id="play" onclick="document.getElementById('song').play()"></div>
<div>
<h2 id="title"></h2>
<h3 id="artist"></h3>
</div>`
Javascript
$("#white").click(function(){
$("#song").attr('src',data[0].songSrc);
$("h2").html(data[0].title)
$("h3").html(data[0].artist)
});
$("#pink").click(function(){
$("#song").attr('src',data[1].songSrc);
$("h2").html(data[1].title)
$("h3").html(data[1].artist)
});
Could I use a for loop or $.each rather than repeating the same code and manually changing the div id and item's index for each of the 19 items?
Here is my bin where I am working this out: jsbin
Relevant HTML:
<div id="play" onclick="document.getElementById('song').play()"></div>
Why don't you give all your colors a common class and then store the object index in a data attribute. Then you can just have one click event which populates the correct data. Something like this:
$("div.color").click(function(){
var index = $(this).data('src');
$("#song").attr('src',data[index].songSrc);
$("h2").html(data[index].title);
$("h3").html(data[index].artist);
});
<div id="white" class="color" data-src="0"></div>
<div id="pink" class="color" data-src="1"></div>
I'm not entirely sure what you want but this should get you in the right direction.
Html
<div id="content">
<audio id="song" preload="none"></audio>
</div>
<div class="songs"></div>
and then with Javascript/jQuery
var html = '';
//Create a div for each fetched song
$.each(data, function(index,item){
html += '<div class="song" data-song-id="'+index+'" data-artist="'+item.artist+'" data-src="'+item.songSrc+'"></div>';
});
// and add them to the div element with the class songs
$('.songs').html(html);
//Listen to clicks on all divs with the class song
$('.songs').on('click', '.song' function(e){
var $this = $(this);
var songId = $this.data('song-id');
var artist = $this.data('artist');
var src = $this.data('src');
$("#song").attr('src',src);
})
Yes, you can. You have to refactor both, html and js.
At HTML you have to replace the static div's, the ones that have an id. Instead of that, use a container where all songs will be appended.
At JS, create DOM elements for each song, and append it to the songs container. Before, be sure, that all elements has "click" event handler with songs specific data. Take advantage of 'bind'
HTML
<div class="songs"></div>
<div id="play" onclick="document.getElementById('song').play()"></div>
<div>
<h2 id="title"></h2>
<h3 id="artist"></h3>
</div>
</div>
JS
myUrl='http://meyecare.herokuapp.com/api/v1/songs';
$(window).load(function(){
$.ajax({
url: myUrl,
type: 'GET',
dataType: 'jsonp',
success: function(data) {
$.each(data, function(index,item){
var element = $( "<div id='" + item.color + "'></p>" );
element.on('click', function(){
$("#song").attr('src',this.songSrc);
$("h2").html(this.title);
$("h3").html(this.artist);
}.bind(item));
element.appendTo(".songs");
});
},
error: function(){
console.log('Shnope!');
},
});
});
Related
i have a DOM Element
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
I want to get the HTML like $('.list-item').html();
Then i want to fill parts like data-attributes and content with own variables so i can get for example this:
<div class="list-item">
<div class="name">NAME CONTENT</div>
<div class="id" data-id="123456">CONTENT</div>
Link
</div>
Then i want to store that as string in a varibale like
var htmlCode = '<div class="list-item">.....';
The tricky part here is to do that all in Javascript without changing the DOM Element. I hope for help. Thanks!
You can use .clone() to clone your div and then use .attr() to change attr from id class .
Demo Code :
var htmls = $(".list-item").clone()
$(htmls).find(".id").attr('data-id', 'somehting');
console.log($(htmls).html()) //store in variable..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
You can use this
<script>
var html = $('.list-item').html();
console.log(html);
var list = $('<li></li>')
$('.list-item').children().each(function(index,elem){
$(list).append($(elem).clone());
})
$(list).children().each(function(i,e) {
$(e).data("id","1234")
$(e).html("ll");
})
console.log($(list).children());
</script>
Thank you all. With your help i got this solution:
var $temp = $('.list-item').html();
var $code = temp.replace('data-id=""', 'data-id="1234"').replace('href=""', 'href="https://link.de"');
So $code is my varibale wich stores the html as string without changing the DOM Element :)
I'd really appreciate any help!
I have a working jquery script. When a div is clicked, it updates the css class to active and executes a working ajax response.
I also have a filter functionality that works too. When a checkbox is ticked it calls a new list of div's from mysql with all the same class properties. However, when any of these new div's are clicked the ajax response doesn't work. If anyone could help I would be incredibly grateful!
HTML:
<div id="result" class="results">
<div class="w-embed"><img src="images/loader.gif" id="loader" width="" "200px"="" style="display:none;">
<?php
$sql="SELECT * FROM `posts`";
$result=$con->query($sql);
while($row=$result->fetch_assoc()){
?>
<div class="c-card" data-id="<?=$row['id'];?>">
<h1 class="s-h2">
<?=$row['title'];?>
</h1>
<!-- <div class="s-para m-light m-small"><?=$row['description'];?></div> -->
<div class="c-stats">
<div class="s-stat">Pay:
<?=$row['pay'];?>
</div>
<div class="s-stat">Deadline:
<?=$row['deadline'];?>
</div>
<div class="s-stat">Location:
<?=$row['location'];?>
</div>
<div class="s-stat">Cat:
<?=$row['category'];?>
</div>
</div>
<p class="s-para">
<?=$row['description'];?>
</p>
Find Out More
</div>
<?php }?>
</div>
</div>
Javascript:
<script>
$('.c-card').on('click', function(event){
event.preventDefault();
$('.c-card').removeClass('active'); //Removes class to all
$(this).toggleClass('active'); //Applies class
var action = 'data';
var dataId = $(this).data("id");
$.ajax({
type:"POST",
url:"ajax/selected.php",
data:{action:action,id:dataId},
success: function(response){
$("#jobber").html(response);
$("#changeme").text("altered");
}
});
});
</script>
This is the outputted response from the filters:
'<div class="c-card" data-id="'.$row['id'].'">
<h1 class="s-h2">'.$row['title'].'</h1>
<div class="c-stats">
<div class="s-stat">Pay:'.$row['pay'].'</div>
<div class="s-stat">Deadline:'.$row['deadline'].'</div>
<div class="s-stat">Location: '.$row['location'].';</div>
<div class="s-stat">Cat: '.$row['category'].'</div>
</div>
<p class="s-para">'.$row['description'].'</p>
Find Out More
</div>';
So my question is how do i make the new divs (called from the filter) to continue to be triggered and change class + execute the ajax query.
Thanks so much in advance!
I have been thought your actual problem was the ajax response is getting null.
<div class="c-card" data-id="<?=$row['id'];?>">
You are using the data-id attribute in the HTML section. But the script handles the id attribute using for getting the id. So the id is getting null for ajax call, Please use the below code or change the data-id attribute to id in the HTML section as you like.
var action = 'data';
var dataId = $(this).data("data-id");
"id" and "data-id" are different attributes for HTML. Please use same attributes in HTML and script
maybe because there is no html(div|| p || span ||...) element that have id of id="jobber"
I have a page of about 15-20 YouTube videos I’d like to dynamically update the img src to point to the YouTube hosted thumbnails. From a logic perspective, I want to find every DIV with a class of “videos”, get the ID of that class and update the image source with the dynamically inserted value, e.g., http://img.youtube.com/vi/DbyNtAQyGs/0.jpg in the first example. All IDs are unique because they are the YouTube video IDs and there is only one img tag under each “videos” class.
This code would run on page load so it would have to be pretty fast to ensure the values are set before the browser passes the each img tag in the DOM. Hoping I can get one of those one liners instead of vars and multiple lines.
<div id="DbyNtAQyGs" class="videos">
<img src="" width="212" height="124" />
</div>
<div id="Fh198gysGH" class="videos">
<img src="" width="212" height="124" />
</div>
Current Code
$('.videos img').attr('src', 'http://img.youtube.com/vi/' + $(this).closest('div').attr('id')); + '/0.jpg');
You can use:
$('.videos img').attr('src', function() { return 'http://img.youtube.com/vi/' + $(this).closest('div').attr('id') + '/0.jpg'; })
Loop through the .videos elements:
$('.videos').each(function(){
var $this = $(this),
_id = $this.attr('id'); // Capture the ID
// Construct the img src
$this.find('img').attr('src', 'http://img.youtube.com/vi/' + _id + '/0.jpg');
});
Bonus: chain in the click event for your anchor:
$this.find('a').click(function(e){
e.preventDefault();
loadPlayer(_id);
}).find('img').attr('src', 'http://img.youtube.com/vi/' + _id + '/0.jpg');
So you can simplify your markup:
<div id="DbyNtAQyGs" class="videos">
<img src="" width="212" height="124" />
</div>
I'm trying to program a playlist for a site I'm presently working on, and I'm having some issues presently. I've written the script so far and it replaces the default song with a second song, but does not revert back on click.. any suggestions?
The HTML...
<audio id="player" src="../audio/small-skeletal.mp3" type="audio/mp3" controls autoplay></audio>
<div id="audio_list" style="margin-top: 100px;">
<div id="track">
<h2 class="change-song" data-track="http://www.birp.fm/music/playlists/2014/january-2014/027%20-%20Phantogram%20-%20Fall%20In%20Love.mp3">Switch to second song</h2>
<h2 id="bb" class="change-song" data-track="http://www.logicwebmedia.com/dev/ecb/new-dev/audio/small-skeletal.mp3">Change it back!!</h2>
</div>
$('.change-song').click(function(){
var song = $('.change-song').data('track');
$('#player').attr('src', song).attr('autoload', 'auto').attr('autoplay');
});
The script only ever returns the first song as the value, and never the second.. how do I fix this?
Change your click function to:
$('.change-song').click(function(){
var song = $( this ).data('track');
$('#player').attr('src', song).attr('autoload','auto').attr('autoplay');
});
this is a reference to the element that was clicked.
You need to use this as a reference to the clicked .change-song element in the click handler. Your current code is selecting both elements at once and when you retrieve the track data attribute it only gets it from the first element in the matched set.
$('.change-song').click(function(){
var song = $(this).data('track');
$('#player').attr('src', song).attr('autoload','auto');
});
Change your $('.change-song').data('track'); to $(this).data('track'); which will give you correct scope. Sorry for changing song files in the snippet.
$('.change-song').click(function() {
var song = $(this).data('track');
$('#player').attr('src', song).attr('autoload', 'auto').attr('autoplay');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttonmit2ani">
<audio id="player" src="audio/acdc.ogg" controls autoplay></audio>
<div id="audio_list" style="margin-top: 100px;">
<div id="track">
<h2 id="aa" class="change-song" data-track="audio/acdc.ogg">Switch to second song</h2>
<h2 id="bb" class="change-song" data-track="audio/radiohead.ogg">Change it back!!</h2>
</div>
</div>
</div>
In a Blog you can determine a tag for each post e.g. Video, Photo, Quote etc... If I created a div class for each tag e.g.
<div class="Video"></div>
<div class="Photo"></div>
<div class="Quote"></div>
How can I create a onclick link so when I click it only shows div's called Video and hides all other div's?
DEMO HERE
Using Jquery....
$(document).ready(function()
{
$('.filter').click(function(e)
{
e.preventDefault();
var filter = $(this).html();
$('.boxes').hide();
$('.'+filter).show();
});
});
Then in your HTML
<a class="filter">Video</a>
<a class="filter">Photo</a>
And your divs....
<div class="boxes Video">Blahblah</div>
<div class="boxes Photo">Blahblah</div>
Or you can do it using data attributes, to keep your HTML more readable...but this works too
DEMO HERE
I'd recommend using jQuery for this. And it would be much better if you give all your "tag" divs a class like, for example, tag and separated with a space it's specific type.
For example class="tag audio". But this should work for now:
$('div').click(function () {
var tags = ['Video', 'Photo', 'Quote'], tag = $(this).attr('class');
if ($.inArray(tag, tags)) {
$('.' + tag).show();
$('div').not('.' + tag).hide();
}
});