Many a hrefs from JSON, on toggle click make diffrent id appear - javascript
I have a JSON file with movies in theaters. I want to make info appear for right movie when I click on movie title which are many. My code is not working, but I am able to make all the movies appear on click, no matter what movie.
I want to be able to click, let's say, "Ender's Game", and then make info div appear with only info about that film. My code is here below:
JavaScript:
$(document).ready(function() {
$.getJSON('json/store.json', function(results) {
//Get movie title
for (var i = 0; i < results['results'].length; i++) {
var title = '<p>' + results['results'][i].title + '</p>';
$('#movies').append(title);
}
for (var i = 0; i < results['results'].length; i++) {
var title = $('#info').append("<p class='biohus'>" + results['results'][i].title + "</p>");
var img = $('#info').append("<img id='myndbio' width='200' height='300' class='img' src =" + results['results'][i].image + ">");
}
$('.title').click(function(){
$(this).parent().find('#info').slideToggle("slow");
});
$('.title').click(function(){
var dataMovieId = $(this).attr('data-movie-id');
$('#'+dataMovieId).slideToggle("slow");
});
});
});
Html:
<div id="bio" class = "content">
<center><h1 class="cinemaheadline">Myndir í bíó</h1></center>
<?php include 'php/curl.php';?>
<div id="movies" class="movies">
<!-- Movies -->
</div>
<div id="info" class="info">
<!-- info -->
</div>
</div>
and php for connection to api:
<?php
//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");
//url
$url = 'http://apis.is/cinema';
$storejson = 'json/store.json';
//skrifa
$fw = fopen($storejson, 'w');
//start curl
$ch=curl_init($url);
//set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute
$r=curl_exec($ch);
//close curl
curl_close($ch);
$arr = json_decode($r,true);
fwrite($fw, json_encode($arr, TRUE));
?>
The main problem you have here is that you need some way of linking the title with the info. Either have the title and info wrapped in its own div for each movie, or use some attribute (data-movie) and give it a name or number which can associate the title and the info.
If the first way you'll need to do something like
$('.title').click(function(){
$(this).parent().find('.info').slideToggle("slow");
});
and the second way would be something like;
$('.title').click(function(){
var dataMovieId = $(this).attr('data-movie-id');
$('#'+dataMovieId).slideToggle("slow");
});
Lastly you should not be using ids the way you are. eg you will be outputting img tags with the same ids. You should only use an id once on a page.
EDIT: Full code;
$(document).ready(function() {
$.getJSON('json/store.json', function(results) {
for (var i = 0; i < results['results'].length; i++) {
// title link. note the data-id attr which is i, which we will put into the movie info, to tie them together
var title = '<p>' + results['results'][i].title + '</p>';
// info section
var infoTitle = "<p class='biohus'>" + results['results'][i].title + "</p>";
var infoImg = "<img id='myndbio' width='200' height='300' class='img' src =" + results['results'][i].image + ">";
// wrap title and image in a div with the data-id attr and i
var info = '<div class="movie-info data-id="'+i+'">'+infoTitle+infoImg+'</div>';
// place both title and info sections in the right spots
$('#movies').append(title);
$('#info').append(info);
}
});
// set up click handlers
$('#movies a').click(function(){
// find data id of clicked movie
var id = $(this).attr('data-id');
// find movie info with correct id and show
$('#info .movie-info[data-id="'+id+'"]').slideToggle("slow");
});
});
Related
How to get user profile Information from JSON API using Jquery?
I am creating a simple script to display a list of active users from JSON API if you click one of the listed users its should display user information eg username, name, description, city, email, avatar and a static map with the location selected With Google APIs for static maps. What should I do to accomplish that? I am able to get the list of active users, so far this is what I have done. NOTE: I am a newbie. $.getJSON('profile.json', function(data) { var output = '<ul>'; $.each(data, function(key, val) { //check the user if is active then display the active users if(val['active'] == true) { output += '<li>'+ val.first_name + " " + val.last_name + " " + val.username +'</li>'; } }); }); sample json.api {"id":987,"username":"jstephensre","active":false,"password":"8de90ec658d72b54ef0b270611ef9eb6241fa59b77b5c98b9bffb4fd631a4b10","first_name":"Johnny","last_name":"Stephens","last_login":"6/7/2016","email":"jstephensre#opensource.org","avatar":"https://robohash.org/nihilpariaturrepudiandae.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"117187617-3","color":"#6adf06","drugs":["Zicam Cold Remedy Ultra Rapidmelts","BUTALBITAL, ACETAMINOPHEN AND CAFFEINE"]},"coordinates":{"lat":"8.65972","lng":"-75.12809"}}, {"id":988,"username":"dtorresrf","active":true,"password":"443f2261332613a2da952d05a25ceec2d8eb9ed177ce830b3b4d6fbbe536e2c0","first_name":null,"last_name":"Torres","last_login":null,"email":"atorresrf#facebook.com","avatar":"https://robohash.org/idnihilut.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":null,"color":"#a04fce","drugs":["Cockroach, American","Lisinopril and Hydrochlorothiazide"]},"coordinates":{"lat":"9.86667","lng":"6.71667"}}, {"id":989,"username":"jsmithrg","active":false,"password":"4e9750746ad03f82717ebd702c03c92749de1cbc820798ab409fb5e6760101ad","first_name":null,"last_name":"Smith","last_login":null,"email":"tsmithrg#creativecommons.org","avatar":null,"gender":["Male"],"favorites":{"book-isbn":null,"color":"#3bff1e","drugs":["Yellow Pine","Meprobamate","GenRx Daily Defense Antifungal"]},"coordinates":{"lat":"-16.00528","lng":"-41.29722"}}, {"id":990,"username":"sroserh","active":false,"password":"ab83a77062c8ee868f3b966d50a8ee39f63e3cec81349b83b81adcd3c6fa5da3","first_name":"Sarah","last_name":null,"last_login":"12/19/2015","email":"sromerorh#about.me","avatar":null,"gender":[],"favorites":{"book-isbn":"117541910-9","color":"#ac8603","drugs":["MORUS ALBA POLLEN","enema","Altipres-B"]},"coordinates":{"lat":"32.26616","lng":"35.00893"}}, {"id":991,"username":"sholmesri","active":false,"password":"11802fc53531079cdf8033e6772ffc5ac47c8ea8a453b66e8ac8df9ae29d9543","first_name":"Susan","last_name":"Holmes","last_login":"1/28/2016","email":"sholmesri#mozilla.com","avatar":"https://robohash.org/doloreshicqui.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"658583882-3","color":"#04da21","drugs":["Tempra","Estradiol Transdermal System"]},"coordinates":{"lat":"-39.23686","lng":"-70.9197"}}, {"id":992,"username":"rhayesrj","active":true,"password":"beae358b1eb873bac4fa640410520157f26738ee4d2de1144f30101c6af8e259","first_name":"Rachel","last_name":"Hayes","last_login":"12/7/2015","email":null,"avatar":"https://robohash.org/teneturautest.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"291847889-X","color":null,"drugs":["BUDESONIDE","Doxorubicin Hydrochloride","Hydrocodone Bitartrate and Acetaminophen"]},"coordinates":{"lat":"-20.58333","lng":"48.53333"}}, {"id":993,"username":"jcampbellrk","active":false,"password":"9602ccbe7599aefea9a25eb05ab2ede44302f57fd153bad07aa0f5a2f46be537","first_name":"Joan","last_name":"Campbell","last_login":"8/29/2016","email":"jcampbellrk#bravesites.com","avatar":"https://robohash.org/numquamutquae.png?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"588841638-X","color":"#7c5963","drugs":[]},"coordinates":{"lat":"57.6531","lng":"14.6968"}}, {"id":994,"username":"ejamesrl","active":false,"password":"55b1d2418621cda82225bf569f5f30c5b5fcfe5ae7aef6b1e3418a97335b47ab","first_name":"Elizabeth","last_name":"James","last_login":"1/14/2016","email":"ejamesrl#geocities.jp","avatar":null,"gender":["Female"],"favorites":{"book-isbn":"026417147-0","color":"#ba1d5c","drugs":["Losartan Potassium and Hydrochlorothiazide","Ramipril"]},"coordinates":{"lat":"54.64043","lng":"32.87811"}}, {"id":995,"username":"krogersrm","active":true,"password":"c5a8921245a345fb133193f8ceb14021469b4f42a7d945e835b9497081fb7130","first_name":"Kathleen","last_name":null,"last_login":"6/13/2016","email":"khansenrm#nationalgeographic.com","avatar":"https://robohash.org/mollitiasuscipitmagnam.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"636138809-3","color":"#1c858e","drugs":["Tramadol Hydrochloride","iBlanc Restora-Bright"]},"coordinates":{"lat":"12.71402","lng":"121.51242"}}, {"id":996,"username":"sperkinsrn","active":false,"password":"c0f48289a4145ffd34374f7236ea4e650df57cff11f4f77b865a44dde410cfb8","first_name":"Sarah","last_name":"Perkins","last_login":"8/31/2016","email":null,"avatar":"https://robohash.org/consequaturculpavelit.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"561211079-0","color":null,"drugs":["Caduet"]},"coordinates":{"lat":"43.30472","lng":"124.32778"}}, {"id":997,"username":"jlanero","active":false,"password":"0430117ff30143b0f3727527f62346351582a396cc60a5bf599e674cc34c07c5","first_name":"Jack","last_name":"Lane","last_login":"3/20/2016","email":null,"avatar":null,"gender":[],"favorites":{"book-isbn":"819102101-3","color":null,"drugs":["RIFAMPIN"]},"coordinates":{"lat":"51.8796","lng":"4.5059"}}, {"id":998,"username":"wroserp","active":true,"password":"626e6d1a1a92ff6e741ae21e3bbbae265000ca0f87306590c2344d4130dd57a9","first_name":"Willie","last_name":"Rose","last_login":"10/16/2016","email":null,"avatar":null,"gender":["Male"],"favorites":{"book-isbn":"108540866-3","color":null,"drugs":["OXYGEN","Garnier Fructis Antidandruff"]},"coordinates":{"lat":"57.58167","lng":"83.76917"}}, {"id":999,"username":"sphillipsrq","active":false,"password":"de0a87749bb04b2630ac6dbeb7259947383189afb6c2b458d80a15f6881b0439","first_name":"Stephanie","last_name":"Phillips","last_login":"11/24/2016","email":"sphillipsrq#wikia.com","avatar":"https://robohash.org/laborerepellendustemporibus.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"721916787-3","color":"#9eee74","drugs":[]},"coordinates":{"lat":"51.0016","lng":"21.71474"}}, {"id":1000,"username":"phicksrr","active":false,"password":"2a27d007956e55da298aa3fb427a5a8ed7a8d661f4d4a2e340a98026996521eb","first_name":"Phyllis","last_name":"Hicks","last_login":"2/14/2016","email":null,"avatar":"https://robohash.org/sedsednon.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":"268196481-4","color":null,"drugs":["Ibuprofen"]},"coordinates":{"lat":"-6.22625","lng":"106.0253"}}]
1st : First set the unique id in href attribute 2nd : Onlcik of anchor tag prevent the default behaviour of anchor tag . and grab the id from href attribute . 3rd : Again loop the json data and compare with currently clicked id if it is current id then break the loop using return false; then prepare the information like below . var data =[{"id":987,"username":"jstephensre","active":false,"password":"8de90ec658d72b54ef0b270611ef9eb6241fa59b77b5c98b9bffb4fd631a4b10","first_name":"Johnny","last_name":"Stephens","last_login":"6/7/2016","email":"jstephensre#opensource.org","avatar":"https://robohash.org/nihilpariaturrepudiandae.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"117187617-3","color":"#6adf06","drugs":["Zicam Cold Remedy Ultra Rapidmelts","BUTALBITAL, ACETAMINOPHEN AND CAFFEINE"]},"coordinates":{"lat":"8.65972","lng":"-75.12809"}}, {"id":988,"username":"dtorresrf","active":true,"password":"443f2261332613a2da952d05a25ceec2d8eb9ed177ce830b3b4d6fbbe536e2c0","first_name":null,"last_name":"Torres","last_login":null,"email":"atorresrf#facebook.com","avatar":"https://robohash.org/idnihilut.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":null,"color":"#a04fce","drugs":["Cockroach, American","Lisinopril and Hydrochlorothiazide"]},"coordinates":{"lat":"9.86667","lng":"6.71667"}}, {"id":989,"username":"jsmithrg","active":false,"password":"4e9750746ad03f82717ebd702c03c92749de1cbc820798ab409fb5e6760101ad","first_name":null,"last_name":"Smith","last_login":null,"email":"tsmithrg#creativecommons.org","avatar":null,"gender":["Male"],"favorites":{"book-isbn":null,"color":"#3bff1e","drugs":["Yellow Pine","Meprobamate","GenRx Daily Defense Antifungal"]},"coordinates":{"lat":"-16.00528","lng":"-41.29722"}}, {"id":990,"username":"sroserh","active":false,"password":"ab83a77062c8ee868f3b966d50a8ee39f63e3cec81349b83b81adcd3c6fa5da3","first_name":"Sarah","last_name":null,"last_login":"12/19/2015","email":"sromerorh#about.me","avatar":null,"gender":[],"favorites":{"book-isbn":"117541910-9","color":"#ac8603","drugs":["MORUS ALBA POLLEN","enema","Altipres-B"]},"coordinates":{"lat":"32.26616","lng":"35.00893"}}, {"id":991,"username":"sholmesri","active":false,"password":"11802fc53531079cdf8033e6772ffc5ac47c8ea8a453b66e8ac8df9ae29d9543","first_name":"Susan","last_name":"Holmes","last_login":"1/28/2016","email":"sholmesri#mozilla.com","avatar":"https://robohash.org/doloreshicqui.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"658583882-3","color":"#04da21","drugs":["Tempra","Estradiol Transdermal System"]},"coordinates":{"lat":"-39.23686","lng":"-70.9197"}}, {"id":992,"username":"rhayesrj","active":true,"password":"beae358b1eb873bac4fa640410520157f26738ee4d2de1144f30101c6af8e259","first_name":"Rachel","last_name":"Hayes","last_login":"12/7/2015","email":null,"avatar":"https://robohash.org/teneturautest.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"291847889-X","color":null,"drugs":["BUDESONIDE","Doxorubicin Hydrochloride","Hydrocodone Bitartrate and Acetaminophen"]},"coordinates":{"lat":"-20.58333","lng":"48.53333"}}, {"id":993,"username":"jcampbellrk","active":false,"password":"9602ccbe7599aefea9a25eb05ab2ede44302f57fd153bad07aa0f5a2f46be537","first_name":"Joan","last_name":"Campbell","last_login":"8/29/2016","email":"jcampbellrk#bravesites.com","avatar":"https://robohash.org/numquamutquae.png?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"588841638-X","color":"#7c5963","drugs":[]},"coordinates":{"lat":"57.6531","lng":"14.6968"}}, {"id":994,"username":"ejamesrl","active":false,"password":"55b1d2418621cda82225bf569f5f30c5b5fcfe5ae7aef6b1e3418a97335b47ab","first_name":"Elizabeth","last_name":"James","last_login":"1/14/2016","email":"ejamesrl#geocities.jp","avatar":null,"gender":["Female"],"favorites":{"book-isbn":"026417147-0","color":"#ba1d5c","drugs":["Losartan Potassium and Hydrochlorothiazide","Ramipril"]},"coordinates":{"lat":"54.64043","lng":"32.87811"}}, {"id":995,"username":"krogersrm","active":true,"password":"c5a8921245a345fb133193f8ceb14021469b4f42a7d945e835b9497081fb7130","first_name":"Kathleen","last_name":null,"last_login":"6/13/2016","email":"khansenrm#nationalgeographic.com","avatar":"https://robohash.org/mollitiasuscipitmagnam.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"636138809-3","color":"#1c858e","drugs":["Tramadol Hydrochloride","iBlanc Restora-Bright"]},"coordinates":{"lat":"12.71402","lng":"121.51242"}}, {"id":996,"username":"sperkinsrn","active":false,"password":"c0f48289a4145ffd34374f7236ea4e650df57cff11f4f77b865a44dde410cfb8","first_name":"Sarah","last_name":"Perkins","last_login":"8/31/2016","email":null,"avatar":"https://robohash.org/consequaturculpavelit.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"561211079-0","color":null,"drugs":["Caduet"]},"coordinates":{"lat":"43.30472","lng":"124.32778"}}, {"id":997,"username":"jlanero","active":false,"password":"0430117ff30143b0f3727527f62346351582a396cc60a5bf599e674cc34c07c5","first_name":"Jack","last_name":"Lane","last_login":"3/20/2016","email":null,"avatar":null,"gender":[],"favorites":{"book-isbn":"819102101-3","color":null,"drugs":["RIFAMPIN"]},"coordinates":{"lat":"51.8796","lng":"4.5059"}}, {"id":998,"username":"wroserp","active":true,"password":"626e6d1a1a92ff6e741ae21e3bbbae265000ca0f87306590c2344d4130dd57a9","first_name":"Willie","last_name":"Rose","last_login":"10/16/2016","email":null,"avatar":null,"gender":["Male"],"favorites":{"book-isbn":"108540866-3","color":null,"drugs":["OXYGEN","Garnier Fructis Antidandruff"]},"coordinates":{"lat":"57.58167","lng":"83.76917"}}, {"id":999,"username":"sphillipsrq","active":false,"password":"de0a87749bb04b2630ac6dbeb7259947383189afb6c2b458d80a15f6881b0439","first_name":"Stephanie","last_name":"Phillips","last_login":"11/24/2016","email":"sphillipsrq#wikia.com","avatar":"https://robohash.org/laborerepellendustemporibus.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"721916787-3","color":"#9eee74","drugs":[]},"coordinates":{"lat":"51.0016","lng":"21.71474"}}, {"id":1000,"username":"phicksrr","active":false,"password":"2a27d007956e55da298aa3fb427a5a8ed7a8d661f4d4a2e340a98026996521eb","first_name":"Phyllis","last_name":"Hicks","last_login":"2/14/2016","email":null,"avatar":"https://robohash.org/sedsednon.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":"268196481-4","color":null,"drugs":["Ibuprofen"]},"coordinates":{"lat":"-6.22625","lng":"106.0253"}}]; var output = '<ul>'; $.each(data, function(key, val) { if(val['active'] == true) { output += '<li><a class="new_href" href="'+val.id+'">'+ val.first_name + " " + val.last_name + " " + val.username +'</a></li>'; } }); output +='</ul>'; $('#list').html(output); $(document).on('click','.new_href',function(event){ event.preventDefault(); var current_id = $(this).attr('href'); var details='<ul>'; $.each(data, function(key, val) { if(val['active'] == true && val['id']==current_id) { details+="<li>username : "+val['username']+" </li>"; details+="<li>firstname : "+val['first_name']+" </li>"; details+="<li>lastname : "+val['last_name']+" </li>"; details+="<li>email : "+val['email']+" </li>"; return false; } }); details+="</ul>"; $('#info').html(details); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="list"> </div> <div id="info"> </div>
Detect element that has the same attribute value as another element
I have some content that is loaded from a XML file with XMLHttpRequest: <div uid="29710" > content.... </div> <div uid="19291" > content.... </div> <div uid="099181" > content.... </div> The code used to get the content: xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","notes.xml",false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; var x = xmlDoc.getElementsByTagName("noteboard"); var newHTML = ""; for (i=0;i<x.length;i++) { newHTML += "<div><div uid='"+ x[i].getAttribute('uid')+"'>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>"+ x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +"</div></div>"; } document.querySelector('#panel').innerHTML += newHTML; The content is updated every 3 seconds, but the problem starts when the old content is repeated and piled up, as well as the new content. Also, the UID attribute value is loaded from the same XML file as the content - so all the new repeated content has the same UID as the old repeated content. If I am not clear enough, this is the sort of thing that is happening: <div uid="19291">Old Content</div> <div uid="77191">New Content</div> <div uid="19291">Old Content</div> <div uid="19291">Old Content</div> <div uid="21503">New Content</div> So how would you remove all the divs that have the same UID value as each other, except for the original one ?
You could check if the uid you are adding already exists in the page before adding it. xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","notes.xml",false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; var x = xmlDoc.getElementsByTagName("noteboard"); var newHTML = ""; for (i=0;i<x.length;i++) { // check if the UID exists in the page and only add it if it does not var uid = x[i].getAttribute('uid'); if ( !document.querySelector('#panel *[uid="'+ uid +'"]') ){ newHTML += "<div><div uid='"+ x[i].getAttribute('uid')+"'>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>"+ x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue + "</div></div>"; } } document.querySelector('#panel').innerHTML += newHTML;
One option (using "vanilla javascript", no jQuery), if you are sure that the correct element is first in the DOM, is to use document.querySelectorAll to loop through the elements, removing each of them except the first one. For instance, if you had a <div> with an ID of panel and you wanted to remove divs with a duplicate UID (using 11111 as an example) from inside of this container: var divs = document.querySelectorAll('div[uid="11111"]'); Array.prototype.forEach.call(divs, function(el, idx) { if(idx > 0) { document.getElementById('panel').removeChild(el); } }); Array.prototype is used because document.querySelectorAll returns an array-like NodeList, not an actual Array. (Update following OP's update: this would go after the data has been retrieved from the XML file.)
You can see if your document already has a div with that uid. var div = document.querySelector('div[uid=' + items[i].getAttribute('uid') + ']'); The code above will search the document any div that has an attribute uid with the same value. So, your final code will be something like: var xhr = new XMLHttpRequest(); xhr.addEventListener('load', function(e) { var items = xhr.responseXML.getElementsByTagName("noteboard"); for (var i = 0; i < items.length; i++) { var div = document.querySelector('div[uid=' + items[i].getAttribute('uid') + ']'); var newHTML = ''; if (!div) { // it doesn't exist yet newHTML += "<div><div uid='"+ x[i].getAttribute('uid')+"'>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>"+ x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +"</div></div>"; } } document.getElementById('panel').innerHTML += newHTML; }); xhr.open("GET", "notes.xml", false); xhr.send();
Show / hide image function with remove classname
I'm using the following function to display the image on which the user clicks on in an above div. In the event the user clicks again on the populated image (in the div), I would like to remove the image in the div and have the original image visible again. <img id="<?php echo $id; ?>" src="img/.." url=".." name="..." onClick="changeImage(this)"/> function changeImage(item) { var url_img = $(item).attr('url'); var name_item = $(item).attr('name'); var item_id = $(item).attr('id'); document.getElementById('test').innerHTML += '<div style=\'display:inline-block\'><img src=' + url_img + ' url = ' + url_img + ' onClick=document.getElementById(' + item_id + ').classname=\'\'; /> ' + name_item + '</div>'; $(item).toggleClass('hideitem'); } .hideitem is a class with display:none; The onClick event in the function does not work (I was trying to remove the classname) and I'm not able to remove the div image when it is clicked with the onClick event. Would anyone have an idea to fix this? Thanks
There were some missing quotes and stuff in your code. For this HTML: <img id="myImgID" src="http://placehold.it/350x150" url="http://placehold.it/150x150" name="Example Dot Com" onClick="javascript:changeImage(this)" /> <div id="test"> <p>this is only a test</p> </div> This JS: changeImage = function (item) { var $item = $(item), $test = $('#test'), url_img = $item.attr('url'), name_item = $item.attr('name'), newDiv = $('<div/>').css('display', 'inline-block').text(name_item), newImg = $('<img/>').attr({'src':url_img, 'url':url_img}) .click(function(e){$item.removeClass('hideitem')}).prependTo(newDiv); $test.append(newDiv) $item.toggleClass('hideitem'); } See it in action here
replaceWith inside each don't work with my own tag
Hello I have function which take text with my own tag and convert this tag to a: //<link src="" title=""> -> title function ProceedLinkTag(text) { var items = text.filter("link"); items.each(function () { var currentElement = $(this); var title = currentElement.attr("title"); var source = currentElement.attr("src"); var newElement = $("<a>" + title +"</a>"); newElement.attr("href", source); $(this).replaceWith("<a href='" + source + "'>" + title + "</a>"); //don't work }); } It work fine(it is detect my own tag even without close tag), I don't get any errors, but it is don't replaceWith(). Try it: var text = "<link src='http://lenta.ru/' title='title'>"; ProceedLinkTag($(text)); alert(text); I also try use it with close tag: var text = "<link src='http://lenta.ru/' title='title'/>"; ProceedLinkTag($(text)); alert(text); But it don't work too.
#sqykly find error: Text in my instance was not a part of document. I change it and now it work.
Passing a value from html to javascript function on click?
Basically, on clicking any image on a html page I want the id associated to be passed to a function. This is what I have tried. It seems I am making a minor mistake here as I am getting the first id passed no matter what image I click from the array. I tried $(this).attr("id") as well, but did not work. for(var i=0;i<jsonObj.length-1;i++){ var rows = ''; var bg_img = jsonObj[i].img; var bg_img = decodeURIComponent(bg_img); rows = "<img id='" + jsonObj[i].source_id + "' src='" + bg_img + "'/>"; document.getElementsByClassName('subscription')[i].innerHTML = rows; } $("body").delegate(".subscription", "click", function() { // var id = $(this).attr("id"); alert("Welcome Test " + $('img').attr("id")); return false; });
$("img").click(function() { var id = $(this).attr("id"); });
Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page. Try $('img',this) instead.