I have bunch of code already written (JS fiddle project) and I'm almost done, but I need some kind toggle thing i JS when you click a person's face, then the quote (scroll down at the result if you can't see it) will change to that person's quote.
I've already got a switch in the JS with this part:
$(function() {
var $profiles = $("#profile1, #profile2, #profile3, #profile4, #profile5, #profile6, #profile7, #profile8, #profile9, #profile10, #profile11");
$profiles.click(function(e) {
$profiles.removeClass("focused");
$(this).addClass("focused");
});
});
but I need to combine it with the quotes somehow.
If you really don't want to help me out with specific, I'd be just happy with just pseudo code or help on how to think. I've been sitting with this piece for way too long now to be able to think straight.
What would you recommend?
Cheers all, you guys rock!
I solved your problem like this:
$profiles.click(function(e) {
var profileNr = parseInt($(this).attr("id").substring(7));
$profiles.removeClass("focused");
$(this).addClass("focused");
$(".thequote .show").removeClass("show");
$(".thequote blockquote").eq(profileNr-1).find("p").addClass("show");
});
It extracts the index of the quote from the profile number and then selects the appropriate quote with jQuery eq(). I updated your JS Fiddle as well and tested that it works.
You have to have some kind of reference in your blockquote, for example a data attribute which indicates to which profile the quote belongs. For example:
<blockquote data-profileid="profile8">
<p>
"Sist är starkast... eller något sånt."
</p>
</blockquote>
Then in the onclick function, show the blockquote with the data attribute that matches the clicked id. You can get the clicked id like this:
var id = $(this).attr('id');
Related
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:
Suppose we have an HTML document that contains these two lines:
<Body>
<H1 title = "When this is clicked, the section changes"> Title </ h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</ Body>
Type the code that would change the look of this page so that:
• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".
• When you click on the section, the position of the title changes and gets centered.
Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)
var h1 = document.querySelector('h1');
var first = document.querySelector('#first');
h1.addEventListener('click', function() {
first.innerText = 'First section: modified version.';
});
first.addEventListener('click', function() {
h1.style.textAlign = 'center';
});
As others have mentioned, you should be able to find everything on Google. But to help you out, this is what the answer should be:
var heading = document.getElementsByTagName("h1")[0];
var section = document.getElementById("first");
heading.addEventListener("click", function() {
section.innerText = "First section: modified version";
});
section.addEventListener("click", function() {
heading.setAttribute("style", "text-align: center");
});
<h1 title="When this is clicked, the section changes">Title</h1>
<p id="first" title="When this is clicked, the title is centered">First section: Original version.</p>
Is this what you are looking for?
$(document).on("click", "h1", function() {
$(this).css("text-align", "center");
})
p, h1 {
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 title="When this is clicked, the section changes"> Title </h1>
<p id="first" title="When this is clicked, the title is centered"> First section: Original version. </p>
First of all Please correct your html markup to standards and add some javascript code. Check below snippet:
$(document).on('click', 'h1', function(){
$('#first').text('First section: Modified version.');
});
$(document).on('click', '#first', function(){
$('h1').css('text-align','center');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1 title = "When this is clicked, the section changes"> Title </h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</body>
I really have no idea why you're being downvoted here. From what I gather you've tried your best on all your assigned questions and this one happened to stump you...
Anyways.. this question has a few different problems that need to be solved for you to complete the question. I'm going to try to break these down into the components, and then explain the pieces that help us get to where you want to be.
Question 1
Thinking through this a bit, here are the following steps to solve your problem.
Find a way to "listen" for a "click event" on the <h1> element.
Find a way to change the text within the <p> element to the desired text when the <h1> element is clicked.
There are some substeps buried in this but this should get us started.
To solve this issue, we'll need to find a way to select elements on a page. A Google search yields a few methods to do this in vanilla JS based solely on the code you've given.
Query Selectors: document.querySelector and document.querySelectorAll
Tag selectors: document.getElementsByTagName
There are many others as well, but using only the code that you've supplied, and assuming we're not allowed to add class attributes or anything, we'll roll with the above choices.
The selectors above all return HTML "nodes" from the page. You can think of a HTML nodes as objects that make up an HTML page. They have all sorts of properties and we can perform many operations on them.
Your best bet is to use the first suggestion, document.querySelector because it returns a single HTML node based on the passed selector. Be careful though. If we had more than one of the same element, it would only return the first which isn't at all useful.
Here's some documentation you can read and a few examples to help you understand how it works.
document.querySelector documentation
So now we have a way of selecting the <h1> element on the page.
document.querySelector(h1);
Now, we need a way to listen for events. A search of "listening for events in vanilla JS" would bring you to the addEventListener method, which allows us to listen for events on a given HTML element.
eventListener documentation
Now we can put these two together and we have an <h1> element that listens for events. I'm going to skip ahead a bit and fill in the function so we have.
let title = document.querySelector('h1');
title.addEventListener('click', function() {
alert('I just clicked the title');
});
If you plug that in and click the title, you'll see a modal pop up indicating that you clicked the title. One step down.
Now, we have to find a way to change the "text content" of the <p> element to the desired text. To do this, we first need to select the <p> element and store it in a variable. You now know how to do this so I'll leave you to it.
Now that we have the reference to the node we want to modify, we need to change a property of that node related to the text. A Google search of this will return a few different properties, but I'm going to nudge you in the right direction and let you know you want the elem.textContent property.
Putting this all together, here's the code I have that works and satisfies your requirements for the first question.
let headerTxt = document.querySelector('h1');
let sectionTxt = document.querySelector('p');
headerTxt.addEventListener('click', function() {
sectionTxt.textContent = 'First section: modified version';
});
Question 2
Some similarities from the first question here. We need to...
Select both the <h1> and <p> elements on the page (DONE)
add a click event listener to the <p> element that centers the <h1> element.
We can skip the first piece since we did that in question 1. I'm also going to skip adding an event listener to the <p> since we did something similar to that in the first question.
After adding the event listener, we need a way to change the text-alignment of some text in an HTML element.
A Google search brings us to the textAlign CSS property which we can modify using JS.
textAlign
Putting this all together, here's the complete solution
let headerTxt = document.querySelector('h1');
let sectionTxt = document.querySelector('p');
headerTxt.addEventListener('click', function() {
sectionTxt.textContent = 'First section: modified version';
});
sectionTxt.addEventListener('click', function() {
headerTxt.style.textAlign = 'center';
});
<body>
<h1 title = "When this is clicked, the section changes"> Title </h1>
<p id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </p>
</body>
Hope this helps man. One takeaway of advice I have for you is get used to searching and get used to reading documentation. I'm a beginner too and I've figured that out quickly lol.
Good luck!
So, this could be a simple question, but my jQuery skills are just not quite up there (yet). I'm trying to target a specific word on a web page and add a style to it. The word I'm trying to target appears multiple times on the page. I googled around some and found this:
<script>
var divContent = document.getElementById("styled").innerHTML;
divContent = divContent.replace("Bevestigd","<span class='styled'>Bevestigd</span>");
divContent = divContent.replace("Geannuleerd","<span class='styled-r'>Geannuleerd</span>");
divContent = divContent.replace("Pending","<span class='styled-p'>Pending</span>");
document.getElementById("styled").innerHTML = divContent;
</script>
This works, kind of... It only targets the first time it encounters the word and doesn't repeat it self. I found numerous pieces of code to target a word on a page but this one seems to work the best... Is there any one that could help me out?
Is there a foreach function I'm missing?
I also tried this code:
$('body').html(
function(i,h){
return h.replace(/(Nike)/g,'<span class="nike tm">$1</span>');
});
which seems a bit simpler but that didn't work... Maybe someone has a snippet for this or something?
This is your js code done on jquery. Check out this jsfiddle
$('#styled').html(function(i,v){
v=v.replace(/Bevestigd/g,'<span class="styled">Bevestigd</span>');
v=v.replace(/Geannuleerd/g,'<span class="styled-r">Geannuleerd</span>');
v=v.replace(/Pending/g,'<span class="styled-p">Pending</span>');
return v;
});
This is done with regex.
We can extend it further.
eg. To make the search case insensitive use /Bevestigd/gi instead of /Bevestigd/g.
I am in the process of learning JavaScript and jQuery, so apologies if any of this sounds naive or obvious. I started what I thought was a fairly simple project to practice and hopefully learn something in the process.
What I want to do is this: the user inputs a sentence and hits a submit button. The sentence gets added to a list of other sentences submitted by people (preferably on a separate file, preferably encrypted, but not necessary). Then, the website grabs a random sentence from the list and displays it.
I am not asking on how to build all of this. I have already put most of it together, but I am including it here for reference.
I have a separate javascript file with the array of quotes.
var quotes=new Array();
quotes[0]="<p>Quote 1</p>";
quotes[1]="<p>Quote 2</p>";
quotes[2]="<p>Quote 3</p>";
quotes[3]="<p>Quote 4</p>";
quotes[4]="<p>Quote 5</p>";
quotes[5]="<p>Quote 6</p>";
quotes[6]="<p>Quote 7</p>";
Then I randomly display one using this:
function getQuote(){
var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
And adding <script> getQuote(); </script> to the html.
This all works fine.
The part I cannot seem to figure out is taking user input and adding it to the jQuery array. I am using a contenteditable div instead of an <input> because I want it to have multiple lines of text and have a character limit, which as far as I know can only be done with a contenteditable div (according to the research I did at the time, I may be wrong).
I have looked around and tried many if not all the examples I found of how to do this, and none of them worked. This is the last method I tried, if it helps:
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
So, to reiterate, I want to take user input and add it to a JavaScript array. I have scoured stackoverflow and the interet but nothing has worked. Please help!
UPDATE: Arvind got it right. I still have a lot to learn, and it seems I need to read up on localstorage and cookies. I will also need to use PHP to save the sentences on the server. Thank you to all who answered!
Problem is document.getElementsByClassName("input") gives you a NodeList and not just a single html element. So if you do this document.getElementsByClassName("input").value, you will end up quotes as [undefined, undefined ... undefined]. Assuming you have single element with the class name input, go with index 0. Also as you stated that you are using div with attribute contenteditable, you may try this instead. document.getElementsByClassName("input")[0].innerHTML
Try this example.
var quotes = localStorage.getItem('quotes'); //get old, if any, gives you string
quotes = quotes ? [quotes] : []; // if got quotes then make it as array else make new array
$(function() {
var quote = $('#quote'); //get the quote div
quote.html(quotes.join('') || quote.html()); //set the default text
$('#btn').on('click', function(e) {
quotes.push(quote.html());
localStorage.setItem('quotes', quotes.join('')); //save the quotes
alert(quotes.join(''));
});
});
#quote {
border: 1px solid grey;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div contenteditable='' id='quote'>
<ol>
<li>Quote 1</li>
<li>Quote 2</li>
</ol>
</div>
<input type='button' id='btn' value='Submit' />
P.S.
In order to preserve the old quotes you may possibly use cookie, localStorage, etc.
Are these "quotes" being saved locally?
Yes, to share it among several users visiting by different browsers, you have to save it with the server script like PHP, Java, ASP, etc. Here you can either use ajax, if you wana avoid page reload on submit, else you can go for form submit.
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
should be
$(".submit").click(function() {
quotes.push(document.getElementsByClassName("input").text());
});
EDIT: With a content editable div you need to use text() instead. Here is an example fiddle. https://jsfiddle.net/
var quotes=[];// better
// function to add to array
function addQuote(myquote){
quotes.push('<p>'+myquote+'</p>');
}
addQuote("Quote 1");
addQuote("Quote 2");
addQuote("Quote 3");
addQuote("Quote 4");
addQuote("Quote 5");
addQuote("Quote 6");
addQuote("Quote 7");
addQuote("Quote 8");
$(".submit").on('click',function() {
addQuote(document.getElementsByClassName("input")[0].value);
});
NOTE: suggest NOT using the "input" class name and use some other one as that might be confusing to others at some point later (confused by element named input)
I also added the paragraph tags as that would provide a consistent pattern for your input text. Assumption on my part however.
NOTE I also assume that the element IS an input type with the .value since that is NOT provided (the markup)
I need your help at a problem of my Wordpress Webpage. My Wordpress-page is an Single-Page-App with 3 different boxes of content. The left and center boxes are static, the right one changes its content by clicking on links of the other boxes. I decided, to load all the content in the right box and show them with the CSS-command visibility. With a combination of pathJS and JS, i want the URL to change by clicking on the links. So far so good - all works fine, but i dont get managed via my JS-Function to remove the shown-class.
My script looks like this:
<script>
function showDetailContent(showid) {
//suche objekt right_id -> was du zeigen willst -> getelementbyid
alert("1");
var id = document.getElementsByClassName('shown');
alert("2");
id.classList.remove('shown');
alert("3");
document.getElementByID("right_" + showid).classList.add('shown');
alert("4");
}
//var c = document.getElementById('content'); -->do the function :)
Path.map("#/?p=<?php the_id();?>").to(function () {
showDetailContent(<?php the_id();?>);
});
Path.listen();
</script>
The alerts are just my way of "debugging". I think its not the best way to debugg, but i am very new in the world of prorgamming and this is kind of easy.
However, the first two alerts are shown, if i activate a link. So the (first) mistake is on the line
id.classList.remove('shown');
Normally, the right-box is hidden, so that only one content is load.
Do you understand my problem till here?
I would appreciate fast help!
Greetings, Yannic! :)
Look at this : http://snipplr.com/view/3561/ to know remove class pure javascript
getElementsByClassName gets multiple elements, try:
var id = document.getElementsByClassName('shown')[0];
Or iterate through them if you want to remove class from all elements with class shown;
When I click the href, I want to display the image and description from the target id. Can someone correct this code for me and show me how to do it right? Thank you very much!
HTML:
<div id="gallery"><img/></div>
Click me
jQuery code:
var datas={
"images":[{ "src":"gallery/panorak.jpg",
"title":"PANORAK",
"date":"28/10/2010 Web Design",
"description":"desc",
"id":"panorak",
},
{
"src":"gallery/kamoa.jpg",
"title":"kamoa",
"date":"28/10/2010 Web Design",
"description":"desc",
"id":"kamoa",
},
]};
$(document).ready(function(){
var gallery=$("#gallery")
//****I don't know how to display it right at this point
var list=$("<ul/>");
gallery.append(list);
datas.images.each(function(i,j){
list.prepend($("<li/>").$("<img/>").attr("src",datas.images[i].src).load(function(){ }));
});
});
Any help is greatly appreciated! Thank you very much!
I have made some changes to your code:
http://jsfiddle.net/T5r6D/
Have a look at my jsfiddle link for all updates.
You had some structure in flow issues and javascript error.
I am adding all image in array using normal for loop. once loop is done, i wrap images with <li> and adding the list to the stage.
Keep in mind that images will not be shown coz it is not on the jsfiddle server. Try it on your side.
UPDATE
http://jsfiddle.net/T5r6D/1/
So the new update does not hide the full container.
The anchor #tag [href] will be matched with the images title tag. So once clicked on a button it will hide the image that matches.
Try this:
$(document).ready(function(){
var gallery=$("#gallery")
//****I don't know how to display it right at this point
$('a').click(function(){
var list=$("<ul/>");
gallery.append(list);
$.each(datas.images, function(i,j){
var img = $("<img/>").attr("src",datas.images[i].src);
list.prepend($("<li/>").append(img));
});
});
});
If you want to trigger events when something is clicked, you can use click() function. And I fixed each() function part. Check this documentation. And I split some code to improve readability.