Yes, I want to replace a simple anchor link with a javascript array code. We're doing it the long (and possibly complicated) way over here. I figured it would be a simple scrollTo property but I still cant get the page to scroll or jump anywhere else on the page.
Can someone tell me if I'm doing something horribly wrong?
Here is the javascript.
$(function(){
//Search index for Cards
var gameA = new Array('normal','ex','promo','counterfeit');
$('#go').click(function(e){
var term = $('#term').val();
var searchIndex = gameA.indexOf(term);
console.log(term);
console.log(searchIndex);
if (searchIndex > -1){
console.log("hi");
window.scrollTo(0,"#sec"+searchIndex);
}
});
});
And here is my source code.
<h2 id="top">Select a Term</h2>
<p>List: Normal, Ex, Promo, Counterfeit</p>
<form action="javascript:void(0)">
<label for"term">Enter a term from the list above.</label><br>
<input type="text" id="term" name="term">
<button id="go">Go</button>
</form>
</div>
<br><br>
<img src="images/fancycards.jpg" width="1191" height="670" alt="fancy cards"><br>
<h2 id="sec0">Normal Cards</h2>
<p>Back to Top</p>
<img src="images/cards.jpg" width="1131" height="707" alt="cards"><br>
<h2 id="sec1">Ex Cards</h2>
<p></p>
<img src="images/excards.jpg" width="1000" height="653" alt="ex cards"><br>
It looks like window.scrollTo takes coordinates for both arguments, rather than an element's ID.
Try the following in place of your current scrollTo command:
window.scrollTo(0, $("#sec"+searchIndex).offset().top)
Here's a JSFiddle example that includes this change. The images obviously won't show up, but it does scroll properly: http://jsfiddle.net/1mpqm1te/1/
You need to pass a number to the scrollTo() function, not a string. This would be the Y offset of the element you want to scroll to. Here is an updated version! If we give the card sections semantically sensical ID values ('normal-cards', 'ex-cards', etc), we can easily make this happen!
http://jsfiddle.net/yLvhh53a/
$(function () {
//Search index for Cards
var gameA = new Array('normal', 'ex', 'promo', 'counterfeit');
$('#go').click(function (e) {
var term = $('#term').val();
console.log(term);
var item = $('#' + term + '-cards');
console.log(item);
$('html, body').animate({
scrollTop: item.offset().top
}, 1000);
});
});
<h2 id="top">Select a Term</h2>
<p>List: Normal, Ex, Promo, Counterfeit</p>
<form action="javascript:void(0)">
<label for "term">Enter a term from the list above.</label>
<br>
<input type="text" id="term" name="term">
<button id="go">Go</button>
</form>
</div>
<br>
<br>
<img src="images/fancycards.jpg" width="1191" height="670" alt="fancy cards">
<br>
<h2 id="normal-cards">Normal Cards</h2>
<p>Back to Top
</p>
<img src="images/cards.jpg" width="1131" height="707" alt="cards">
<br>
<h2 id="ex-cards">Ex Cards</h2>
<p></p>
<img src="images/excards.jpg" width="1000" height="653" alt="ex cards">
<br>
This way, you don't even need to reference an array. For every section you add, just ensure it has a consistent ID '[name]-cards' and it will automatically find it. You can also change the scroll speed if you'd like.
When scrolling to an element with an id. You can simply just change the hash of the url and that's it.
Related
How do I retrieve information stored in a js file? I assume I am labelling my node elements in HTML incorrectly
I'm hoping to gain a better understanding of how to retrieve a function node from localStorage
Below are the key factors I am trying to get using getElementById into local storage from post HTML.
This is not everything in my listing.html document, I have excluded everything but what I think are essential elements
<div class="listing">
<div class="container-form">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="img" value(src)="1" id="img" src="images/4.JPG" alt="img1">
</div>
<div class="infoBox">
<h5 post="weight" id="weight" value="7.00">7.00 : Under - 16 oz</h5>
</div>
<div class="column-bottom">
<div class="add-button">
<div class="add-button" method="post">
<p><input type="submit" onclick="addListing()" class="btn"></input></p>
<div class="buy-button">
<span class="price" post="price" id="price" value="60">$60</span>
<button type="button" class="btn" onclick="window.location.href='cart.html'" onclick="addListing()"
;>BuyMe</button>
</div>
</div>
</div>
</div>
</div>
</div>
I am trying to use the function below to store each element from the post HTML
function addlisting() {
let listing = ['listings'];
if (localStorage.getItem('listings')) {
listing = JSON.stringify(localStorage.getItem('listings'));
alert("added!");
}
listing.push({ 'listingId': listingId + 1, image: '<imageLink>' });
listingsId = listingsId + 1;
var listingsName = document.getElementById('name').innerHTML;
var listingsPrice = document.getElementById('price').getAttribute('data- value');
var listingsImage = document.getElementById("img").src;
var listingsWeight = document.getElementById('weight').getAttribute('data- value');
value = parseFloat(listingsPrice, listingsWeight).toFixed(2);
localStorage.getItem('name', 'price', 'img', 'weight', JSON.stringify(listingsName, listingPrice, listingsImage, listingsWeight));
}
here is the $(document).ready(function(){ function I'm hoping to implement into my code, I got this from another Stack Overflow page as it was the most fitting however I am yet to understand each component.
$(document).ready(function () {
$('#Btn').load(function () {
let listings = [];
if (localStorage.getItem('listings')) {
listings = JSON.parse(localStorage.setItem('listings'));
}
listings.push({ 'listingId': 1, image: '<imageLink>' });
});
});
my question again is how do I then execute this function using onload Onto a separate HTML, called cart.html. I did not display my cart.html file because there is nothing pertaining to this question on it. And furthermore how to go about styling Onload events that retrieve information from localStorage.
P.S.
There is an alert function within my first .js excerpt addListing(), that does not fire when clicked. probably a sign of bad programming. I've just never found a straightforward answer
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'p#p_50\')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
JQuery/JS:
function quote(post) { $(post).text(); }
This works to fetch the posts message, but how do I go about finding the Username?
I have tried using $(post).prev('a').text();, and $(post).parent().prev('a').text();, but nothing seems to work.
You can do it without jQuery. If possible, change the html and pass the current link to the function, like this:
<a onclick="quote(\'p#p_50\', this)">Quote</a>
Then you can just search through all links:
function quote(str, currentLink) {
var allLinks = document.getElementsByTagName("a"); // get all links in document
var index = allLinks.indexOf(currentLink);
if (index > 0) {
var prevLink = allLinks[index-1];
console.log(prevLink); // log it to browser console
} else {
console.log("there is no previous link");
}
}
By looking at the DOM structure, it should work with $(post).parent().prev().text().
Alternative way, how about you wrap all of them with <div>, like this: XD
<div id="message1">
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'#message1\')">Quote</a> //change to wrapper id
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
</div>
then to get the post text: $(post).find('#p_50').text();
to get the username: $(post).find('a:first').text();
Looking at your sample HTML, if you're at p, just go to parent element and get the closest a and you should be fine:
function quote(post) {
var post = $(post).text();
var user = $(post).parent().closest('a').text();
}
Perhaps using parent() and then previous()
var ancortext = $(post).parent().prev().text();
A function example below.
function username(post) {
return $(post).parent().prev().text();
}
Note: This smells to me, your code is very much tied into the structure of the HTML this way. If you alter the HTML, chances are your javascript will break.
I have copied your code into my own HTML document, and confirmed that the jquery method calls above output the desired result. If you are not, then something is different with your source HTML and the source that you posted, or your jquery functions differ from the ones stated in this answer :)
your onclick attribute is wrong,because onclick accept javascript,so the value could be support js,then onclick="quote('p#p50')".
function quote(post) {
var subject = $(post).text();
var user=$(post).parent().prev('a').text();
console.log('posted '+subject+' by '+user);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote('p#p_50')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
I've been trying to hide divs that contain particular string using the other solutions suggested on this site, however none worked (most likely due to my inexperience with jQuery)
I'd like to completely hide all divs that (in this example) contain the string 'zynthesized'
<div class="photos-wrapper" id="detailPhoto-977355202965894535_11842652">
<div class="pseudo">
zynthesized
</div>
<div class="image-wrapper">
<img src="https://scontent.cdninstagram.com/hphotos-xfp1/t51.2885-15/s150x150/e15/11195725_518243828313545_1133319712_n.jpg"></div>
<div class="activites">
<span class="popular_picto ss-star "></span>
<div class="album-relative detail-photo-album-977355202965894535_11842652" style="display: none;">
<input type="hidden" class="apalbumsPhoto" value="977355202965894535_11842652">
<input type="hidden" class="apalbumsPhoto-977355202965894535_11842652" value="">
</div>
<span class="nb_comment_score">0</span>
<span class="comment_picto ss-chat"></span>
<span class="nb_like_score">4</span>
</div>
<div class="nouveau-commentaire">
<textarea id="comment-977355202965894535_11842652" class="textareaCommentaire" placeholder="Your comment"></textarea>
<img src="http://static.iconosquare.com/images/loading.gif" class="commentLoading">
</div>
</div>
From what I've seen something like
$('.photos-wrapper:contains("zynthesized")').hide()
Should be closest to what I need, but I've had no luck with it.
Any help would be amazing!
Thanks for the help guys! Turns out that the script was working however as the page loaded new divs automatically when scrolling, the script had to be run after the page loaded them.
The final script looks like
$(window).load(function(){
$(".photos-wrapper:contains('zynthesized')").hide();
});
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150;
if(y_scroll_pos > scroll_pos_test) {
$(".photos-wrapper:contains('zynthesized')").hide();
}
});
Hopefully this helps anyone looking to do something similar!
You can simply use a regex.
<script>
var ptrn = /zynthesized/g;
$( "div" ).each(function( index ) {
if(ptrn.test($( this ).text())){
$( this ).hide();
}
});
</script>
Here is simple snippet : jsfiddle.net/dariubs/hgbm3doa
I seem to be able to hide the resource container using
resource.parent().parent().hide();
but I don't understand why the input value is not clearing with
resource.parent().siblings('.resource-value').children('input').val('');
when I use
resource.parent().siblings('.resource-value') I get the parent of the input value but adding .children('input').val('') on top of that does nothing or if I add .children('input:text').val('')
I have very similar code for something else which works just fine, looked at other questions and not sure what I'm missing.
function removeResource(resource) {
'use strict';
//hide resource on screen
resource.parent().parent().hide();
//set resource text value to ''
resource.parent().siblings('.resource-value').children('input').val('');
}
(function($) {
'use strict';
$(function() {
$('#resources').on('click', '.remove-resource', function(evt) {
// Stop the anchor's default behavior
evt.preventDefault();
// Remove the image, toggle the anchors
removeResource($(this));
});
});
})(jQuery);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="resources">
<div class="resource">
<div class="resource-value">
<input type="text" name="resources[]" value="1" />
</div>
<p class="hide-if-no-js"><a title="remove resource" href="javascript:;" class="remove-resource">remove resource</a > </p>
<!-- .hide-if-no-js -->
</div>
<div class="resource">
<div class="resource-value">
<input type="text" name="resources[]" value="2"/>
</div>
<p class="hide-if-no-js"><a title="remove resourcee" href="javascript:;" class="remove-resource">remove resource</a> </p>
<!-- .hide-if-no-js -->
</div>
</div>
</body>
<html/>
Tried your code and worked fine for me in terms of the actual value of the field clearing, though in inspector the HTML element still has the value attribute showing.
You can use
.attr('value','')
to clear that too http://jsfiddle.net/bvtg93dm
You just have to change the value witch jquery to set "" (so, empty).
input.attr('value','')
Try to log your sibling element with
Try to change your removeResource function to
function removeResource(resource) {
'use strict';
//hide resource on screen
var parent = resource.parent().parent();
parent.hide();
// log your element
console.log(parent.find('.resource-value input'));
// make sure you are getting an element you need
console.log(parent.siblings('.resource-value').childer('input').get(0);
//set resource text value to ''
parent.find('.resource-value input').val('');
}
I have a page that has 50 elements with the same class "fields" which are all display none at the moment
<div class="fields" style="display:none;">
...
</div>
<div class="fields" style="display:none;">
...
</div>
<div class="fields" style="display:none;">
...
</div>
<div class="fields" style="display:none;">
...
</div>
...
How to I only show the first 3 or whatever number. Plus count them with a count on top like the following example below.
So for example if I needed the first 3 this is what i need the divs to look like
<div class="fields">
<h1>Station 1</h1>
</div>
<div class="fields">
<h1>Station 2</h1>
</div>
<div class="fields">
<h1>Station 3</h1>
</div>
<div class="fields" style="display:none;">
...
</div>
...
So basically only some the number of divs that I need...I already have the number of elements I need to show in this blur statement in the station_count variable. Also notice i need a span tag with the count..any ideas on how to do this
$("#number_station").blur(function(){
var station_count = $(this).val();
//code goes there
});
How to I only show the first 3 or whatever number.
$('div.fields:lt(3)').show();
Plus count them with a count on top
$('div.fields:lt(3)').each(function (index)
{
$('<h1></h1>', {text: 'Station ' + index}).prependTo(this);
}).show();
Demo: http://jsfiddle.net/mattball/TssUB/
Read the jQuery API docs for basic questions like this:
:lt() selector
.prependTo()
jQuery() (for creating new elements)
While the other answers will work, I recently discovered and love the jQuery slice() method.
$(".fields").slice(0, 3).each(function(index) {
// Do whatever you want to the first three elements
}
With
$(".fields").each(function() {
//do whatever like count then show/hide
});
you can iterate over the hidden divs. So with a simple variable you can start/stop whenever you need.