I want to display json.articles[i].title of each news on my website here is my screenshot of website and my code:
In main.js:
(function() {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key', function(json) {
$("#sidebar-wrapper li").each(function() {
$('li').html(json.articles[0].titles)
});
});
})();
My HTML file :
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<strong>Latest Headines</strong>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
</ul>
</div>
Here is my screenshot of website I want to display each news title from json.articles[].title instead of "Your news title".(For clarification see screenshot and HTML code).
Try Below Code
(function () {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b', function (json) {
var html = "";
$(json.articles).each(function (index, value) {
$(".sidebar-nav").append("<li><a href='"+value.url+"'>" + value.title + "</a></li>");
});
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
</ul>
</div>
If all you want is to iterate through the articles you can use an iterator index and keep incrementing it. Something like this.
(function(){
var i = 0;
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b',function(json) {
$("#sidebar-wrapper li").each(function(){
$('li').html(json.articles[i++].titles)
});
});
})();
But you it would be better to iterate over the articles object and create lists dynamically.
You should dynamically create the LI elements, as the no of article from JSON response may vary.
To create element use jQuery(html)
//Cache the ul element
var ul = $("#sidebar-wrapper ul.sidebar-nav");
//iterate the articles
$.each(json.articles, function(index, article) {
//Create anchor
var anchor = $('<a>', {
href: article.url,
text: article.title
});
//Create LI and append anchor after append the LI to UL
$('<li>').append(anchor).appendTo(ul);
});
(function() {
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b', function(json) {
var ul = $("#sidebar-wrapper ul.sidebar-nav");
$.each(json.articles, function(index, article) {
var anchor = $('<a>', {
href: article.url,
text: article.title
});
$('<li>').append(anchor).appendTo(ul);
});
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidebar-wrapper">
<strong>Latest Headines</strong>
<ul class="sidebar-nav">
</ul>
</div>
You can also update li data by using class
Try This
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b',function(json) {
var x=document.getElementsByClassName("title");
for(var i=0;i<x.length;i++)
x[i].innerHTML = json.articles[0].titles;
}); }); </script>
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<strong>Latest Headines</strong>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
<li>
Your news title
</li>
</ul> </div>
Related
How to change home img src, href and anchor text and in list of HTML and how to Add item in list using javaScript
javascript: (function() {
document.getElementsByClassName('home')[0].src = 'imagelink.png';
})();
javascript: (function() {
document.getElementsByClassName('home')[0].href = 'http://www.cnn.com/';
})();
javascript: (function() {
document.getElementsByClassName('home')[0].innerHTML = 'Main';
})();
<ul class="m_menu_ul box_sizing">
<li class="home">
<img src="ld_menu_icon_qa_teal.png">
Home
</li>
<! -- adding this item as well -->
<li class="qa">
<img src="ld_menu_icon_qa_teal.png">
Ask the Editor
</li>
</ul>
I want to like this
the document.getElementsByClassName('home') is not a list because you have just a single element with that class name
to make it work you have to select the correct elements:
document.querySelector('.home img').src = 'imagelink.png';
document.querySelector('.home a').href = 'http://www.cnn.com/';
document.querySelector('.home a').innerHTML = 'Main';
To add an item to the list :
const node = document.createElement('li');
node.appendChild(document.createTextNode('core vocabulary'));
document.querySelector('.m_menu_ul').appendChild(node);
The issue is, that you change the element with the class home which is a <li>. Use query selector and select the correct child elements (img and a):
javascript: (function() {
document.querySelector('.home img').src = 'imagelink.png';
})();
javascript: (function() {
document.querySelector('.home a').href = 'http://www.cnn.com/';
})();
javascript: (function() {
document.querySelector('.home a').innerHTML = 'Main';
})();
<ul class="m_menu_ul box_sizing">
<li class="home">
<img src="ld_menu_icon_qa_teal.png">
Home
</li>
<li class="qa">
<img src="ld_menu_icon_qa_teal.png">
Ask the Editor
</li>
</ul>
I'm try to catch 'banner name' in under code.
<div class = 'pdf-area'>
<ul class = 'pdf list'>
<li>
<span class="icon-left"></span> 'banner name'
</li>
</ul>
</div>
and here is my try.
$("div.pdf-area ul a").click(function(i) {
var txt = $(i.target).text();
console.log(txt);
});
When I run this code, I don't get the value I want.
How can I extract 'baaner name'?
(href= # -> it's not my code and don't have any autohrity that can modify this code . I only can extract value in this condition.)
You do not need to add the click event by using the selector. Simply pass this as the first parameter. Then inside the function use find() on that object to target the span.
Try the following:
function pdfDownload(el, link){
var name = $(el).find('span.icon-left').text();
console.log(name);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'pdf area'>
<ul class = 'pdf list'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
OR: If you do not want to change the HTML
$(".pdfarea > ul a > span").click(function() {
var txt = $(this).text();
console.log(txt);
});
function pdfDownload(){}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'pdfarea'>
<ul class = 'pdflist'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
If the banner name outside the span try the following:
$("div.pdf-area ul a").click(function() {
var txt = $(this).text();
console.log(txt);
});
function pdfDownload(){}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'pdf-area'>
<ul class = 'pdf list'>
<li>
<span class="icon-left"></span> 'banner name'
</li>
</ul>
</div>
<div class = 'pdf-area'>
<ul class = 'pdflist'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
$(document).on('click','.pdflist a',function(){
alert($(this).text());
})
Above click event will give the text on the current element
Fiddle : https://jsfiddle.net/gokulmaha/vt3b0keu/2/
You can remove the $("div.pdf-area ul a").click(function(i).. and create pdfDownload function which will handle both
function pdfDownload(e, path) {
console.log(path)
e.preventDefault();
var txt = $(e.target).text();
console.log(txt);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pdf-area'>
<ul class='pdf list'>
<li>
<span class="icon-left"> 'banner name'</span>
</li>
</ul>
</div>
Hi Try this -
$("div.pdf-area ul a").click(function(i) {
var txt = $("div.pdf-area > ul.list > li a span.icon-left").text();
console.log(txt);
});
I'm having some real hard time adding class active to the li that contains the current page the site is on. URL = http://polissagethibodeau.com/
Here is the relevant HTML
<nav class="nav">
<ul class="sf-menu">
<li id="home">
Home
</li>
<li>
About us
</li>
<li>
Services
<ul>
<li>
Car, Truck and Vans
</li>
<li>
Semi, Boats, RV and Busses
</li>
<li>
Airplanes and Helicopters
</li>
<li>
Aluminum and Plexiglass polishing</li>
</ul>
</li>
<li>
Photos
</li>
<li>
Contact Us
</li>
</ul>
</nav>
CSS I am trying to apply
.sf-menu > li.active > a {
background: #c2e078;
}
Here is the script I am trying to use to no success.
$(function() {
var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
});
YOU can do it by two or many way. Example project
Source LINK
1.----
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("nav ul a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
2.----
here's the code if u want to use plain javascript
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
3.----
function setActive() {
$('#nav').find('a').each(function () {
//console.log(document.location.href)
if (document.location.href == "http://......" + $(this).attr('href')) {
$(this).parents("ul").removeClass("hidden-ul");
$(this).parents().addClass("active");
}
});
}
window.onload = setActive;
Use a if statement to check if it is in the url:
<script>
$(function() {
var path = window.location.pathname.substring(1);
if(window.location.href = path) {
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
}
});
</script>
Its because the HREF property of each of those links is going to be equal to a complete URL, not just file.php
You can get around this by using the $= operator which means (ends with)
Note in the DEMO I changed the var path assignment to just services.php so that it would work in the snippet.
Also, use the $(document).ready(function() { trigger to properly add a listener to an event
Note I realize that this example will cause all of the links to services.php to have the class active added to them. To get around this assign a custom class called navlink to each link in the navigation bar and then use
$('.navlink[href$="' + path + '"]:parent').addClass('active');
$(document).ready(function() {
//var path = window.location.pathname.substring(1);
var path = 'services.php#large';
$('a[href$="' + path + '"]:parent').addClass('active');
});
.active {
font-size: 1.75em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<ul class="sf-menu">
<li id="home">
<a href="./" >Home</a>
</li>
<li>
About us
</li>
<li>
Services
<ul>
<li>
Car, Truck and Vans
</li>
<li>
Semi, Boats, RV and Busses
</li>
<li>
Airplanes and Helicopters
</li>
<li>
Aluminum and Plexiglass polishing</li>
</ul>
</li>
<li>
Photos
</li>
<li>
Contact Us
</li>
</ul>
</nav>
$(document).ready(function () {
// Get previously stored url
if (sessionStorage.getItem("active-class-url"))
{
strLastUrl = sessionStorage.getItem("active-class-url");
$('.nav > li >a[href="' + strLastUrl + '"]').parent().addClass('active');
}
});
$(document).on(".nav > li > a", "click", function () {
// Remove active class from all ancher tag
$(".nav > li > a").parent("li").removeClass('active');
// Add active class to currenly clicked acnher tag
$(this).parent("li").addClass('active')
// Store value of active calss url. So on page refresh you can get it
sessionStorage.setItem("active-class-url", $(this).attr("href"));
})
The problem is your selector.
Instead of this:
$(".nav > li > a")
Use this:
$(".nav > ul > li > a")
Also remove the . (dot) before your paths, and this will work:
$(document).ready(function() {
var pathname = window.location.pathname;
$(".nav > ul > li > a").each(function() {
var $this = $(this);
if ($this.attr("href") === pathname) {
$this.parent().addClass("active");
}
});
});
Test:
$(document).ready(function() {
var url = window.location.toString();
$('#home a').attr('href',url)
$('#home a').text(url)
$('ul.sf-menu a').filter(function() {
if (this.href != '') {
if (this.href == url) {
console.log(this.href)
console.log(url)
$(this).addClass('active');
}
}
});
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<ul class="sf-menu">
<li id="home">
Home
</li>
<li id="stacksnippets">
stacksnippets
</li>
</ul>
</nav>
try above method I hope it helps you.
Here is my code :
<ul>
<li class="active">
<div class="course_video_heading"><span class="minus"></span> Introduction <div class="course_duration" align="right">1m 21s</div></div>
<ul>
<li class="course_video viewed">
Welcome <div class="course_duration" align="right">1m 21s</div>
</li>
<li class="course_video viewed">
I need to select this <div class="course_duration" align="right">1m 21s</div>
</li>
</ul>
</li>
<li>
<div class="course_video_heading"><span class="plus"></span> Warm up <div class="course_duration" align="right">1h 15m</div></div>
<ul>
<li class="course_video viewed current">
Roll down <div class="course_duration" align="right">57s</div>
</li>
<li class="course_video">
Roll down with demi pointe variation <div class="course_duration" align="right">57s</div>
</li>
<li class="course_video" data-file="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" data-image="http://content.bitsontherun.com/thumbs/nPripu9l-480.jpg">
Side roll down <div class="course_duration" align="right">57s</div>
</li>
<li class="course_video">
Side roll down variation with contraction <div class="course_duration" align="right">57s</div>
</li>
<li class="course_video">
Class exercise <div class="course_duration" align="right">57s</div>
</li>
</ul>
</li>
<li>
<div class="course_video_heading"><span class="plus"></span> Brushes <div class="course_duration" align="right">1h 5m</div></div>
<ul>
<li class="course_video">
Welcome <div class="course_duration" align="right">1m 21s</div>
</li>
</ul>
</li>
</ul>
My requirement : There is a element, <li class="course_video viewed current">, I need the previous li which has course_video class. In this case it would be :
<li class="course_video viewed">
I need to select this <div class="course_duration" align="right">1m 21s</div>
</li>
What have I tried :
$(".current").prev(".course_video")
This is not working as it is in different li
Note : It is not the duplicate of following questions :)
jQuery to find nearest Div of Parent
Getting next closest select element with jquery
jquery find closest previous sibling with class
Try this : read the index of current li and if it is 0 then find the previous li of its parent li and then find the course_video. And if index is not 0, then find previous li using prev()
var index = $(".current").index();
if(index==0)
{
var previousLi = $(".current").closest('li').prev('li').find("li.course_video:last");
}
else
{
var previousLi = $(".current").prev(".course_video");
}
var vindex;
$().ready(function () {
$("li .course_video").each(function (index) {
if ($(this).hasClass('current')) {
vindex = index;
}
});
$("li .course_video").each(function (index) {
if (index == vindex - 1) {
alert($(this)[0].outerHTML);
}
});
});
this code will help you.
$('.current').parents('li').prev().find('li:last')
Here's the jsFiddle
You can do it easily with a function that checks the index of the item: if the index is 0 then you'll select the last li in the previous ul.
Element.prototype.previousLi = function() {
var i = $(this).index(),
n = this.parentElement.previousSibling.children.length;
if (i) return this.parentElement.children[i-1];
else return this.parentElement.previousSibling.children[n-1];
}
Then you can do:
var el = $(".course_video.viewed.current")[0];
var previous = el.previousLi();
Try this code , it will give you the desired result :
<script>
var currentLI = $("li.current");
prevLi=$(currentLI).parent('ul').parent('li').prev('li').find('li.viewed:last');
alert($(prevLi).html());
</script>
I'm trying to create a simple filtering systemt that would hide posts that do not have the same id as the li's under the navig class. To achieve this I am looping through all .article li's and checking what's their id.
Example:
click on li with id="health"
Article 2 disappears
Thank you!
HTML:
<ul class="navig">
<li id="health">Health</li>
<li id="ASD">ASD</li>
</ul>
<br>
<ul class="article">
<li id="health">Article 1</li> <br>
<li id="ASD">Article 2</li> <br>
<li id="health">Article 3</li>
</ul>
Javascript:
$('.navig li').onclick(function () {
$id = this.id;
$('.article li').each(function() {
if ($id != this.id) {
$('.article li').hide();
}
});
});
The fundamental problem is your HTML is invalid. You can't use the same id value on more than one element. Separately, you've used onclick where you would want to use click.
I'd probably use a data-article-id attribute on the navigation li instead, like this:
For example: Live copy (source)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Testing</title>
</head>
<body>
<ul class="navig">
<li data-article-id="health">Health</li>
<li data-article-id="ASD">ASD</li>
</ul>
<br>
<ul class="article">
<li id="health">Health Article</li>
<li id="ASD">ASD Article</li>
</ul>
<script>
$('.navig li').click(function () {
var articleId = $(this).attr("data-article-id");
alert(articleId);
var articles = $(".article li");
articles.not("#" + articleId).hide();
$("#" + articleId).show();
});
</script>
</body>
</html>
You'll want to do something to hide the articles (or show a default one) when the page loads, etc.; I'll leave that as an exercise for you. :-)
Side note: br elements cannot be children of ul elements, I've removed the ones from the articles list.
$('.navig li').onclick(function () { <-- not valid jquery
There is no onclick method in jQuery...there is .click(function(){}) or on("click", function(){})
second porblem, ids need to be singular. They can not be repeated. Use a data attribute [and br's can not be children of ul]
<ul class="navig">
<li id="health">Health</li>
<li id="ASD">ASD</li>
</ul>
<br>
<ul class="article">
<li data-id="health">Article 1</li>
<li data-id="ASD">Article 2</li>
<li data-id="health">Article 3</li>
</ul>
and script
$('.navig li').on("click", function() {
var id = this.id;
$(".article li").hide().filter('[data-id="' + id + '"]').show();
});
JSFiddle: http://jsfiddle.net/q8SCF/