Change div content by clicking on a button - without jQuery, please - javascript

There is an i button in the middle of my website. I'd ask you to click it—you would see a button—contact.
When the user clicks on it, I want the content of the div above to be changed.
This is the code:
<section id="about" class="wrapper about accelerate hide">
<div class="cell accelerate">
<div class="cables center accelerate">
<div class="panel accelerate">
<header>
<h1>gog<em>sem</em>cel</h1>
</header>
<p><strong>gogsemcel </strong>is a trademark of <i font-family="Trebuchet MS">Company</i>.</p>
<p>This project is a collaboration between<br>Company name & gogsemcels.</p>
<ul class="links">
<li><a class="download" href="info/info.html">More Info</a></li>
<li><a class="github" target="_blank" href="contact.html">Contact</a></li>
</ul>
</div>
</div>
</div>
</section>
The button's class is github.
Any suggestions?
Gigantic thanks.

I see you have jQuery on your page so you could use this:
$('#about a.github').on('click', function(e){
e.preventDefault();
var content = $(this).closest('.panel').find('p');
content[0].innerHTML = 'This is a new text!'
content[1].innerHTML = 'This is the second line!'
});
Example
I am not a fan of disabling right-click. Just FYI I can see the whole content anyway...
If you want to do it with vanilla JS you can use this (credits do Chris's nice function):
function collectionHas(a, b) { //helper function (see below)
for (var i = 0, len = a.length; i < len; i++) {
if (a[i] == b) return true;
}
return false;
}
function findParentBySelector(elm, selector) {
var all = document.querySelectorAll(selector);
var cur = elm.parentNode;
while (cur && !collectionHas(all, cur)) { //keep going up until you find a match
cur = cur.parentNode; //go up
}
return cur; //will return null if not found
}
var git = document.querySelector('#about a.github');
git.addEventListener('click', function (e) {
e.preventDefault();
var content = findParentBySelector(git, '.panel').querySelectorAll('p');
content[0].innerHTML = 'This is a new text!'
content[1].innerHTML = 'This is the second line!'
});
Example

You should add href attribute to Contact link.
<a class="github" target="_blank" href="#contact">Contact</a>
Then, add id attribute to 2 p elements for easily selecting.
<section id="about" class="wrapper about accelerate hide">
<div class="cell accelerate">
<div class="cables center accelerate">
<div class="panel accelerate">
<header>
<h1>viva<em>stem</em>cell</h1>
</header>
<p id="abc"><strong>vivastemcell </strong>is a trademark of <i font-family="Trebuchet MS">Tsovn Tsirani Company</i>.</p>
<p id="def">This project is a collaboration between<br>Tsovn Tsirani & vivastemcells.</p>
<ul class="links">
<li><a class="download" href="info/info.html">More Info</a></li>
<li><a class="github" target="_blank" href="contact.html">Contact</a></li>
</ul>
</div>
</div>
</div>
</section>
Now, in onload event of your page, add following code. This use pure Javascript that you want.
// You can use document.querySelector -> returns the first element found.
var gh = document.querySelectorAll('#about .github')[0];
if (gh) {
gh.addEventListener('click', function (e) {
e.preventDefault();
document.getElementById('abc').textContent = new Date().getTime();
document.getElementById('def').textContent = new Date().getTime();
})
}

Related

How to display specific div onclick using js

I have multiple with various div inside. On click of more or less a tag I want to display specific i.e. display_on_click
And I want to add that class only for 2 minutes after that remove that class and hide div
My HTML code as below:
$('body').on("click", ".more, .less", function() {
var obj = $(this);
obj.closest('.product_info').find('.display_on_click').addClass('display_on_click_show');
});
.display_on_click {
display: none
}
.display_on_click.display_on_click_show {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<ol class="item_wrapper">
<li class="product_info">
<div class="title">
<h3>Title here</a>
</div>
<div class="incre_decre">
<a class="more">+</a>
<a class="less">+</a>
</div>
<div class="display_on_click">Updated</div>
</li>
<li class="product_info">
<div class="title">
<h3>Title here</a>
</div>
<div class="incre_decre">
<a class="more">+</a>
<a class="less">+</a>
</div>
<div class="display_on_click">Updated</div>
</li>
<li class="product_info">
<div class="title">
<h3>Title here</a>
</div>
<div class="incre_decre">
<a class="more">+</a>
<a class="less">+</a>
</div>
<div class="display_on_click">Updated</div>
</li>
</ol>
</div>
Anyone have idea what I am doing wrong then let me know.
And I want to add that class only for 2 minutes after that remove that class and hide
I would do it like this:
$('body').on("click", ".more, .less", function() {
let parentLi = $(this).parent().parent();
let elementToManipulate = obj.find('.display_on_click');
elementToManipulate.addClass('display_on_click_show');
setTimeout(()=> {
elementToManipulate.removeClass('display_on_click_show')
}, 120000);
});
Instead of using closests I'm grabbing the parent of the parent which is the <li>. You can use closest to grab it. Once I am in the parent li, I find the child with the .display... class (the elementToManipulate object).
Then I add the classes and create a setTimeout to remove the class after 120.000 miliseconds (60sec * 2 * 1000msec)
<button onClick='OpenDiv'>Open</button>
function OpenDiv(){
let div = document.getElementById('BoxOne')
if (div.style.display == 'flex') {
div.style.display = 'none';
else
div.style.display = 'flex';
}
I hope this will work 👍

How to store each paragraph into an javascript array when onclick event occurs?

I have tried the following code. When the user clicks on any paragraph then this paragraph must be stored into a javascript array. If I clicked another paragraph then it must also stored into any array with out losing the last one.
function makeSelection(e) {
var test = [];
for (var i = 0; i < e.children[0].length) {
test.push(test[i])
}
console.log(test)
}
<a href="#" onclick="makeSelection(this)">
<p>This is p1</p>
</a>
<a href="#" onclick="makeSelection(this)">
<p>This is p2</p>
</a>
<a href="#" onclick="makeSelection(this)">
<p>This is p3</p>
</a>
Your loop is missing ;i++
You are pushing test[i] to itself. That does not sound right
I believe you wanted to do this - I copied your HTML from another question you wrote. NOTE I cannot test the paragraph anymore since you have other tags in the paragraph
window.addEventListener("load", function() {
var test = [];
[...document.querySelectorAll(".container p")].forEach(function(para) {
para.addEventListener("click", function(e) {
var text = e.currentTarget.textContent;
if (test.indexOf(text) === -1) test.push(text); // or !test.includes(text) (not IE)
else alert("Already added");
console.log(test)
})
})
})
#container p {
cursor: pointer;
text-decoration: underline;
}
<div class="container">
<p>
<b>Group:N</b>Code:1234<br/>
<b>Session Type:</b>CS<br/>
<b>Location:</b>Main Hall<br/>
<b>Time:</b>14:00<br/>
<b>Day:</b>Tuesday<br/>
<b>Duration:</b>1hour<br/>
</p>
</div>
<div class="container">
<p>
<b>Group:M</b>Code:98743<br/>
<b>Session Type:</b>NP<br/>
<b>Location:</b>Main Hall2<br/>
<b>Time:</b>11:00<br/>
<b>Day:</b>Monday<br/>
<b>Duration:</b>1hour<br/>
</p>
</div>
Using anchor tag (a) useless here which is not designed for this purpose. You can implement onclick attribute directly to p tag. If you want to call makeSelection function for each p tag, you don't need to iterate.
You can simply do this:
for JS:
let data = [];
function makeSelection(text) {
data.push(text.textContent);
console.log(data);
}
for HTML:
<p onclick="makeSelection(this);">TEST1</p>
<p onclick="makeSelection(this);">TEST2</p>
<p onclick="makeSelection(this);">TEST3</p>
Please try this.
function makeSelection(e) {
let item = document.querySelectorAll('a');
console.log(item);
var test = [];
for (var i = 0; i < item.length; i++) {
test.push(item[i].children[0].textContent)
}
console.log(test)
}
<a href="#" onclick="makeSelection(this)">
<p>This is p1</p>
</a>
<a href="#" onclick="makeSelection(this)">
<p>This is p2</p>
</a>
<a href="#" onclick="makeSelection(this)">
<p>This is p3</p>
</a>

How to take a href attribute and use it in a div when clicking on it?

In javascript I want to tell post-container that when I click on it, take the href located at link and go to page X.
There are multiple post-container
My code is this:
<div class="post-container">
<a class="link" href="X">
<h2 class="post-title">Hello, world!</h2>
</a>
<div class="date-posts">...</div>
</div>
I want to be able to click outside the Hello, world! title of my post in any area of ​​post-container and go to page X
Any idea how to do this?
I hope I'm interpreting your question correctly, but you can just rearrange where you're writing your a href tag. Instead, wrap your div inside of it. This will make the entire div element a link.
<a class="link" href="google.com">
<div class="post-container">
<h2 class="post-title">Hello, World!</h2>
<div class="date-posts"></div>
</div>
</a>
This will work.Add Event listener to the parent element (Event Delegation).You can take the href property of the child element and then use window.location.href.You might need to add preventDefault() to avoid default behaviour of a tag
If you have multiple tags with same class name.You have to use querySelectorAll .Either way if you have single elements or multiple elements with same class name use querySelctorAll.
// if you have one tag
let ele = document.querySelectorAll(".post-container")
ele.forEach(element => {
element.addEventListener("click", function(e) {
e.preventDefault();
let href = element.children[0].getAttribute("href")
window.location.href = href;
})
})
.post-container {
background-color: green;
}
<div class="post-container">
<a class="link" href="X">
<h2 class="post-title">Hello, world!</h2>
</a>
<div class="date-posts">...</div>
</div>
Assuming you have multiple .post-containers you would need to iterate over each of them and add an event listener to handle click events. On click, find the a get its href and set the window.location (I just console log it in this demo)
(function(){
let elems = document.querySelectorAll(".post-container");
for (i = 0; i < elems.length; ++i) {
let el = elems[i];
el.addEventListener("click", function(e) {
e.preventDefault();
let href = el.querySelector("a").getAttribute("href");
console.log("href",href);
//window.location.href = href;
})
}
})();
<div class="post-container">
<a class="link" href="X">
<h2 class="post-title">Hello, world!</h2>
</a>
<div class="date-posts">...</div>
</div>
<div class="post-container">
<a class="link" href="Y">
<h2 class="post-title">Goodbye world!</h2>
</a>
<div class="date-posts">...</div>
</div>
Javascript:
var elements = document.getElementsByClassName('post-container');
var loadLink = function() {
var link = this.getElementsByTagName("a")[0].href;
window.location.href = link;
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', loadLink, false);
}
Check working demo
document.getElementsByClassName('post-container')[0].onclick = function(e){
location.href = this.children[0].href;
}

Combine multiple for loops to remove classes on click

I'm looking for some advice regarding having 2-3 for loops in one javascript statement to find elements with a particular class then add and remove classes. I'm fairly new to javascript so bear with me.
What I have so far works but I just don't want to get into bad habits down the line. As an example I have a navigation link that has a class of to--kenya, there is also another element with the same class and when either of these 2 elements are clicked i want the same thing to happen which will be to add an active--section class to the associated section named kenya.
The first for loop will look for all the elements with the class name to--kenya and add a click listener to them. If neither of these 2 elements has the class active--section it then runs another for loop looking for all the sections that have a class called active--section and removes it if it has the class. Then a third for loop runs checking all the navigation links to find a link with the active--link class then removes it if it has it. Once this is complete i just add a class to my new active navigation link as well as add the active--section class to the now active section.
Hope this makes sense, I'm just looking for the cleanest way of doing this.
<main class="main__wrapper">
<nav class="navigation">
<div class="navigation__inner">
<div class="navigation__logo">
Safari
</div>
<ul class="navigation__destinations">
<li class="navigation__destinations--item">
Home
</li>
<li class="navigation__destinations--item">
Kenya
</li>
<li class="navigation__destinations--item">
Botswana
</li>
<li class="navigation__destinations--item">
South Africa
</li>
<li class="navigation__destinations--item">
</li>
</ul>
<ul class="navigation__list">
<li class="navigation__item">
Contact
</li>
</ul>
</div>
</nav>
<div class="up__next">
<div class="up__next__box up__next--kenya to--kenya up__next__box--active">
<div class="up__next__content">
<div class="up__next__info">
<h4 class="up__next__heading">Next</h4>
<span class="up__next__text">Kenya - Maasai Mara National Reserve</span>
</div>
</div>
<div class="up__next__img">
<div class="up__next__img--kenya"></div>
</div>
</div>
</div>
<section class="home sections active--section">
<div class="home__info__box">
<h2 class="heading__primary home__heading--primary">Heading</h2>
<span class="home__info__box--text">text</span>
</div>
</section>
<section class="kenya sections">
<div class="kenya__info__box">
<h2 class="heading__primary kenya__heading--primary">Masai Mara</h2>
<span class="kenya__info__box--text">text</span>
</div>
</section>
</main>
//Global variables
var sections = document.querySelectorAll('.sections');
var navLink = document.querySelectorAll('.navigation__link');
var navHome = document.querySelector('.navigation__link--home');
var navKenya = document.querySelector('.navigation__link--kenya');
var home = document.querySelector('.home');
var kenya = document.querySelector('.kenya');
var toKenya = document.querySelectorAll('.to--kenya');
var upNextKenya = document.querySelector('.up__next--kenya');
//Event listeners
for (var i = 0; i < toKenya.length; i++) {
toKenya[i].addEventListener('click', function () {
if (!kenya.classList.contains('active--section')) {
for (var s = 0; s < sections.length; s++) {
sections[s].classList.remove('active--section');
}
for (var l = 0; l < navLink.length; l++) {
navLink[l].classList.remove('active--link');
}
kenya.classList.add('active--section');
navKenya.classList.add('active--link');
upNextKenya.classList.remove('up__next__box--active');
}
});
}

Grabbing parent pages css with postMessage

I have the following JavaScript which lies on a page within an iframe, and grabs the parent pages css to make the page have a seamless look to the rest of the page. I'm having an issue with it picking up the wrong styling however. How can I target specific tags(such as h1, h3`, etc to use on the page within the iframe?
var getFontFamily = function(){
for(var i = 0; i < document.styleSheets.length; i++){
for(var j = 0; j < document.styleSheets[i].rules.length; j++){
if(document.styleSheets[i].rules[j].style.fontFamily){
return document.styleSheets[i].rules[j].style.fontFamily;
}
}
}
return 'not-found';
};
window.addEventListener('load', function(){
var data = getFontFamily();
window.frames[0].postMessage(data, 'http://localhost:3000');
console.log('Message sent -->');
});
Current version: jsfiddle
This is the HTML that the css of the parent page needs to be applied to:
<div class="info">
<div class="lead">Message Lead</div>
<h2>Title</h2>
<div class="ticker">
<div class="ticker__also">Also</div>
<ul class="ticker__list">
<li>sub headline</li>
<li>sub headline</li>
<li>sub headline</li>
</ul>
</div>
</div>
<div class="extras">
<div class="title">Extra info</div>
<a class="link" href="http://www.url.tv" target="_blank">Link</a>
<div class="share">
<a class="twitter">Twitter</a>
<a class="facebook">Facebook</a>
<a class="email">E-mail</a>
</div>
</div>
You can get styles from elements directly via the style attribute and the window.getComputedStyle method. This is more accurate than just taking the first result that appears in the list of CSS rules (where you also just find selectors, not actual elements the style is applied to).
The MDN page about the style attribute has some easy examples, for your purpose, it could be look like this.
var getFontFamily = function() {
var el = document.getElementById(id);
var cs = window.getComputedStyle(el, null);
return cs.fontFamily || '';
}

Categories

Resources