I wanted to create an updates list, when you see only the title of the update- unless you click on a down-pointing triangle near the title, and then you will see the full update information + the down-pointing triangle will change to an up-pointing triangle. And after clicking on the up-pointing triangle- you will see only the title of the update again + the triangle will be down-pointing.
So I wrote the following code in order to implement that:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
arrowsUpdate();
</script>
<p>
<span class="down-arrow">▼</span>
<br>
<span class="hidden-text">update 1</span>
</p>
<p>
<span class="down-arrow">▼</span>
<br>
<span class="hidden-text">update 2</span>
</p>
</body>
</html>
JS:
function arrowsUpdate(){
$(document).ready(function(){
$(".down-arrow").each(function(){
$(this).click(function(){
$(this).siblings(".hidden-text").slideToggle(0,"linear");
if($(this).html()=="▼")
$(this).html("▲");
else
$(this).html("▼");
});
});
});
}
The problem with this code is that the pointing triangle is always down-pointing. It seems that there is a problem with the if statement- which always returns false.
I don't understand why that happens, especially when the set code lines ($(this).html("▲");and $(this).html("▼");) are working as expected (tried using those code lines in a different page- and it works).
Why the condition $(this).html()=="▼" returns always false, if the content of this is ▼?
You can set html with entities, but when you get it back, it will no longer be entities but characters, that's how entities work.
To be clearer, this line fails every time
if( $(this).html()=="▼" )
because $(this).html() will never return an entity, but the character ▼ instead, proof ...
document.body.innerHTML = '▼';
console.log( document.body.innerHTML )
An easier way to create toggle functionality without relying on the markup, would be to just use a flag
function arrowsUpdate() {
$(".down-arrow").on('click', function() {
$(this).siblings(".hidden-text").slideToggle(0, "linear");
var flag = $(this).data('flag');
$(this).html(flag ? "▼" : "▲").data('flag', !flag);
});
}
Related
I'm using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="shoepoo.js">
</script>
</head>
<body>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
<script type="text/javascript"> shoeName(); </script>
</div>
</body>
</html>
const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
products.forEach(
function names (product) {
document.getElementById("text").innerHTML = product.shoeName;
})
});
};
Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it's a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?
Made below changes in shoepoo.js
products.forEach((product)=> {
document.getElementById("text").innerHTML = product.shoeName;
});
But you need to create dynamic HTML components if there is multiple data in products. Otherwise, it set the last shoeName in the paragraph component.
Good morning to all
I have a question related to my big commerce products title. here I need the first part of the product's title in bold and after the hyphen or dash the second part need in italic. But problem is that the products title comes with one global variable %%GLOBAL_ProductName%% which I cannot make separated with the span tag. so can you suggest me how I can achieve the rest of strings after hyphen show in Italics with the help of javascript?
For example, check this screenshot https://www.screencast.com/t/fKy0FhByzzl
and here is big commerce website http://rp-staging2.mybigcommerce.com/categories
<li class="%%GLOBAL_AlternateClass%%">
<div class="ProductImage" data-product="%%GLOBAL_ProductId%%">
%%GLOBAL_ProductThumb%%
</div>
<div class="OutOfStockMessage InfoMessage" style="%%GLOBAL_ItemSoldOut%%">
%%SNIPPET_SideAddItemSoldOut%%
</div>
<div class="ProductActionAdd" onclick="location.href='%%GLOBAL_ProductLink%%';">
<p>%%GLOBAL_ProductName%%
</p>
<p><em class="p-price">%%GLOBAL_ProductPrice%% USD</em>
</p>
%%GLOBAL_ProductAddText%%
</div>
</li>
%%GLOBAL_ProductName%%
this variable showing products name please check screenshot and website i have provided link
Using some of the cool es6 features (array destructuring and template literals)
$(".pname").each(function () {
[beforeDash, afterDash] = $(this).text().split(" - ");
$(this).html(`${beforeDash} - <i>${afterDash}</i>`);
});
Looks like:
And if you are using jQuery in your website, you can use something like this:
$( window ).on( "load", function(){
var text = $('.text');
var x = text.text().split('-');
text.html(`${x[0]} - <i>${x[1]}<i>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Hello - World
</div>
When ever possible do this kind of split at the server side. Because client side you will manipulate strings after loading the page. So it is not good to do at client side. But anyhow I have written jquery code to fulfill your requirement. I have written in a click event for demo purpose. Please do the logic on onload event.
$("#btn").click(function(){
$(".productName").each(function(){
var title = $(this).text();
var firstSentence = "<b>"+title.substr(0,title.indexOf('-'))+"</b>";
var secondSentence = "<i>"+title.substr(title.indexOf('-')+1)+"</i>";
var finalTitle = firstSentence+ "-" + secondSentence;
$(this).html(finalTitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="productName"> Sample1 - Product Name1</a><br>
<a class="productName"> Sample2 - Product Name2</a><br>
<input id="btn" type="button" value="Change Format">
</body>
</html>
Check this if it helps...
https://jsfiddle.net/Lz8p11mc/1/
You need to split your product name with '-' and then add these isolated names in separate spans and then you can style these spans as you want. I have written code for simple test case , you can modify it as per your requirement.
<html>
<script>
var productName = 'ABC-XYZ';
var separatedNames = productName.split('-');
var firtsName = separatedNames[0];
var secondname = separatedNames[1];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myTag").innerHTML = '<span>'+firtsName+'</span>-<span class="secondnameCls">'+secondname+'</span>';
}
</script>
<body>
<li class="%%GLOBAL_AlternateClass%%">
<p><a id='myTag'></a></p>
</li>
</body>
</html>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
<!-- This is the HTML element -->
<h1 id="greeting"></h1>
JS
var currentUser = localStorage.getItem("currentUser");
document.getElementById("greeting").innerHTML = "Hi " + currentUser;
Here is what happens when inspect the page, it says:
Uncaught TypeError: Cannot set property 'innerHTML' of null(…)
This would be the entire code file.
//mypublicwebsites.tk/artem/databases/a/load_home.js
//This isn't the complete code because I cannot use 'localStorage' in a code snippet
//excluding unneeded code
var isSignedIn = true;
//The current user, lets just say that is me
var currentUser = "Sean";
if(isSignedIn) {
load();
} else {
window.location.replace("index.html");
}
function logOut () {
localStorage.setItem("isSignedIn","false");
localStorage.setItem("currentUser", "none");
window.location.replace("index.html");
}
function load() {
document.querySelector(".greeting").innerHTML = "Hi " + currentUser + "!";
}
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="mypublicwebsite.tk/artem/databases/a/load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
It does seem to work in the snippet but not in the browser.
Fine, I'll post the answer I found. You need to wait for the webpage to load and then execute the script, so I put the script right before the closing body tag.
After checking your source over at Github i notice that there is no element of id greeting at https://github.com/codecademy123/codecademy123.github.io/blob/master/artem/databases/a/home.html :
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
No id but there is a class with the name greeting.
Here's an updated and simplified fiddle:
https://jsfiddle.net/tommiehansen/ndd0c7rh/2/
Basically we just use document.querySelector('.greeting') instead of document.getElementById('greeting') since the id greeting will always return undefined if it does not exist.
If you want to still use an id simply change the source code for home.html from <h1 class="greeting"></h1> to <h1 id="greeting"></h1>. The important part here is to query the DOM after what you've set the class or id to be. Because if you do not match these it will always return as undefined since your javascript will not be able to find the selector.
I am trying to calculate total number of links click by user. To do so i am using following code
<html>
<head>
<script type="text/javascript">
function fnc()
{
document.getElementById("atext").innerHTML="tested";
var iStronglyAgreeCount=parseInt (document.getElementById("ISA") );
document.getElementById("ISA").innerHTML=iStronglyAgreeCount +1;
}
</script>
</head>
<body>
<label id="atext" onClick="fnc()">I strongly agree</label> (<span><label id="ISA">0</label></span>)
</body>
I am storing starting number 0 into a variable and trying to add 1 at each click.But it shows NaN.
Use .textContent to get the text content of the element.
function fnc() {
document.getElementById("atext").innerHTML = "tested";
var iStronglyAgreeCount = parseInt(document.getElementById("ISA").textContent);
document.getElementById("ISA").innerHTML = iStronglyAgreeCount + 1;
}
<a href="#">
<label id="atext" onClick="fnc()">I strongly agree</label>
</a>(<span><label id="ISA">0</label></span>)
Note: If target browser is <IE9, consider using Polyfill
I am trying to loop through a few divs.
Code:
$(".tree div ").each(function () {
var _searchthis = $(this);
var mySearchDiv = _searchthis.parent('div').attr('id');
console.log("this is ID : " + $(this).attr('id'));
console.log("this is parentID : " + mySearchDiv);
});
In case of ID, I am getting the value. But it does not return the .parent('div').attr('id')
I am getting "undefined".
Edited :
When I use .closest() ,instead of .parent(), I get the ID of $(this) only.
.parents('div').first().attr('id') also returns "undefined".
$(".tree li div ").each(function (){
....
}
was a desperate attempt.
HTML Code is more like: http://jsbin.com/yilaw/1/edit
===================================
RESOLVED. I had problem with my HTML structure. Thanks Guys.
Try changing your code to this:
_searchthis.parents("div").eq(0).attr('id');
.parent() parent goes only to the first level while .parents() goes up the stack.
Notice the difference here : http://jsbin.com/labugi/1/edit
html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="firstLevel">
<span id="secondLevel">
<p id="thirdLevel">
<i id="forthLevel">POC</i>
</p>
<span>
</div>
</body>
</html>
javascript
var result = $('#forthLevel').parent('div').attr('id');
console.log('result of .parent("div"): '+ result);
var result = $('#forthLevel').parents('div').attr('id');
console.log('result of .parents("div"): '+ result);
JQuery says about parent : http://api.jquery.com/parent/
The .parents() and .parent() methods are similar, except that the
latter only travels a single level up the DOM tree.
Use parents instead and get the first element like so : _searchthis.parents('div').eq(0);
Please note : the search query that you are using might be very slow, use classes or ids if possible instead of tagNames.