I have tried this:
$(".font").click(function() {
var target = $($(this).data("target"));
$("#text").addClass(target);
})
.pap {
font-family: Papyrus;
}
.ar {
font-family: Arial;
}
.hel {
font-family: Helvetica,
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="font" data-target=".pap">Papyrus</button>
<button class="font" data-target=".ar">Arial</button>
<button class="font" data-target=".hel">Helvetica</button>
<div id="text" class="ar">Text</div>
Unfortunately, it doesn't work to change the classes by clicking a button. Is it just a little mistake or does this logic not work at all?
Three problems:
Wrapping $(this).data("target"),
Including class selector . in target dataset: data-target=".pap",
Adding class rather than replacing class:
$(".font").click(function() {
var target = $(this).data("target"); // no double $ wrap
// replace class because the first class listed takes precedence
$("#text").attr('class', target);
})
.pap {
font-family: Papyrus;
}
.ar {
font-family: Arial;
}
.hel {
font-family: Helvetica,
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- notice no "dot" classname -->
<button class="font" data-target="pap">Papyrus</button>
<button class="font" data-target="ar">Arial</button>
<button class="font" data-target="hel">Helvetica</button>
<div id="text" class="ar">Text</div>
Related
greeting king,
I'm trying to emit click from child(todoitem.vue) element that contains button and slot in this component to parent(app.vue) that will run a method in parent. For example now when I click edit button then method in parent editable() will run and when I click delete button then run method of deletable() in parent. How to approach this. I had tried to pass using v-slot but it only send variable also try emit but failed to emit. I'm totally new to vue..thanks
parent(app.vue)
<template>
<div>
<todolist>
<todoitem v-for="each in a" :key="each.list">
{{each.list}}
</todoitem>
</todolist>
<todolist>
<todoitem v-for="each in b" :key="each.list">
{{each.list}}
</todoitem>
</todolist>
</div>
</template>
<script>
import todolist from "./components/todolist.vue";
import todoitem from "./components/todoitem.vue";
export default {
name: "App",
data(){
return{
a:[
{list:"AAAA"},
{list:"BBBB"},
{list:"CCC"},
],
b:[
{list:"DDDD"},
{list:"EEEE"},
{list:"FFFF"},
],
}
},
components: {
todolist,
todoitem
},
methods:{
editable(){
console.log('editabel')
},
deletable(){
console.log('deletable')
}
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
child(todoitem)
<template>
<slot></slot>
<button #click="test">Edit</button>
<button #click="test2">delete</button>
</template>
<script>
export default {
name: "todoitem",
method:{
test(){
console.log('edit click')
this.$emit('edit-item')
},
test2(){
console.log('delete click')
this.$emit('del-item')
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
todolist
<template>
<slot></slot>
<div>
</div>
</template>
<script>
export default {
name: "todolist",
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
Basically it's structured like this - just put an emit with the function-name and the paramters inside of one of your methods like this:
Child.vue
this.$emit("Your_Function_Name", Parameter_1, Parameter_2);
Than go to your parent.vue call your emitted function and use it inside your methods of the parent.vue:
Parent.vue
<template>
...
<Child #Your_Function_Name="Your_Function_Name">
...
</template>
<script>
methods: {
Your_Function_Name(Parameter_1, Parameter_2) {
console.log(Parameter_1, Parameter_2)
}
}
</script>
Hopefully this helps you out!
I want to show text when one of the elements are 'clicked', but hide the others.
So when I press 'Home' the other elements are on 'hide' and, at the same time, change the active class.
Please help.
function toggle(obj) {
var obj = document.getElementById(obj);
if (obj.style.display == "block") obj.style.display = "none";
else obj.style.display = "block";
}
<div id="navbar">
<a class="active" href="javascript:void(0)" onClick="toggle('Home')">Home</a>
Project
Contact
</div>
<div class="informasjon" id="Home" style="display:none;">
bla bla bla
</div>
<div class="informasjon1" id="Contact" style="display:none;">
<br>
blabla
</div>
<div class="informasjon1" id="Project" style="display:none;">
Different bla bla bla
</div>
You can hide all the elements on each click, then show the clicked one. Also, I will suggest you to avoid inline event handler by using addEventListener. You can use data- attribute to keep the reference of the id of the respective element.
Demo:
.active{
color: red;
}
<div id="navbar">
<a class="active" href="javascript:void(0)" data-id="Home">Home</a>
Project
Contact
</div>
<div class="informasjon" id="Home">
bla bla bla
</div>
<div class="informasjon" id="Contact" style="display:none;">
<br>
blabla
</div>
<div class="informasjon" id="Project" style="display:none;">
Different bla bla bla
</div>
<script>
var links = document.querySelectorAll('#navbar a');
links.forEach(function(el){
el.addEventListener('click', toggle)
})
function toggle() {
links.forEach(el => el.classList.remove('active'));
this.classList.add('active');
var dataEl = document.querySelectorAll('.informasjon');
dataEl.forEach(el => el.style.display = "none");
var id = this.getAttribute('data-id');
var obj = document.getElementById(id);
obj.style.display = "block";
}
</script>
The easiest, and therefore arguably the best, solution would be to avoid using JavaScript for the most part, and use CSS.
I've made some changes to your HTML – removing the JavaScript from your <a> elements, replacing the <div id="navbar"> with a semantic <nav> element, and placing the <a> elements within an <ol>, also I've added a class to your 'content' elements because I couldn't decide if the <div id="Home"> element was meant to have the class of informasjon or if it was a typo given the remaining elements were of class informasjon1 – so the approach below takes advantage of the CSS :target pseudo-class to style the element that is targetted by the fragment-identifier in the URL, the part following the # character:
*,
::before,
::after {
box-sizing: border-box;
font-family: Ubuntu, Roboto, Calibri, Helvetica, Arial, sans-serif;
line-height: 1.5;
margin: 0;
padding: 0;
}
nav ol {
list-style-type: none;
display: flex;
justify-content: space-around;
}
li a {
background-color: lightblue;
border-radius: 0.3em;
color: #000;
display: block;
padding: 0.2em 1em;
}
div.content-unit {
display: none;
}
div.content-unit:target {
display: block;
}
.active {
background: palegreen;
}
<nav>
<ol>
<li>
Home
</li>
<li>
Project
</li>
<li>
Contact
</li>
</ol>
</nav>
<div class="informasjon content-unit" id="Home">
This is in the 'home' area
</div>
<div class="informasjon1 content-unit" id="Contact">
This is in the 'contact' area
blabla
</div>
<div class="informasjon1 content-unit" id="Project">
This is in the 'project' area
</div>
As CSS works with the majority of the functionality, there are a couple aspects that require JavaScript; on page-load we need to show the correct 'content' to match the 'active' button on page-load (assuming that a hash isn't reliably set on page-load), and we need to add the 'active' class to the correct <a> when the links are followed.
First, a simple JavaScript function to show the 'active' <a> element:
// defining a named function, using Arrow syntax, passing in the
// Event Object from the (later) use of EventTarget.addEventListener():
const showActive = (e) => {
// here we're searching the <nav> element to find all elements
// with the class of 'active', and then iterating over that
// NodeList with NodeList.prototype.forEach():
document.querySelectorAll('nav .active').forEach(
// here we again use Arrow syntax, and pass in a
// reference to the current element of the NodeList;
// we then use the classList API to remove the 'active'
// class from the element's class-list:
(activeElem) => activeElem.classList.remove('active')
)
// we're binding the event-handler (this function) to the <a>
// elements, but an <a> element can have descendant elements,
// so here we find the EventObject.currentTarget which is the
// element to which the event-listener was bound (the <a>)
// and we again use the classList API to add the 'active' class:
e.currentTarget.classList.add('active');
}
// here we use document.querySelectorAll() to find all <a> elements
// within the <nav> element, and then use NodeList.prototype.forEach()
// to iterate over that NodeList:
document.querySelectorAll('nav a').forEach(
// here we again use an Arrow function, to bind the showActive()
// function (note the deliberate lack of parentheses) as the
// event-handler for the 'click' event:
(aElem) => aElem.addEventListener('click', showActive)
);
*,
::before,
::after {
box-sizing: border-box;
font-family: Ubuntu, Roboto, Calibri, Helvetica, Arial, sans-serif;
line-height: 1.5;
margin: 0;
padding: 0;
}
nav ol {
list-style-type: none;
display: flex;
justify-content: space-around;
}
li a {
background-color: lightblue;
border-radius: 0.3em;
color: #000;
display: block;
padding: 0.2em 1em;
}
div.content-unit {
display: none;
}
div.content-unit:target {
display: block;
}
.active {
background: palegreen;
}
<nav>
<ol>
<li>
Home
</li>
<li>
Project
</li>
<li>
Contact
</li>
</ol>
</nav>
<div class="informasjon content-unit" id="Home">
This is in the 'home' area
</div>
<div class="informasjon1 content-unit" id="Contact">
This is in the 'contact' area
blabla
</div>
<div class="informasjon1 content-unit" id="Project">
This is in the 'project' area
</div>
I have changed the class of Home for this to work, but hopefully it helps you in case this isn't exactly what you need.
function toggle(obj) {
let arrClass = document.getElementsByClassName("informasjon1");
let object=document.getElementById(obj);
let navbar = document.getElementById("navbar");
for (let i = 0; i < navbar.childNodes.length; i++) {
if(navbar.childNodes[i].innerHTML == obj) navbar.childNodes[i].className = "active";
else navbar.childNodes[i].className = "inactive";
}
for (let i = 0; i < arrClass.length; i++) {
if (arrClass[i].id == object.id) arrClass[i].style.display = "block";
else arrClass[i].style.display = "none";
}
}
<div id="navbar">
<a class="active" href="javascript:void(0)" onClick="toggle('Home')">Home</a>
Project
Contact
</div>
<div class="informasjon1" id="Home" style="display:none;">
bla bla bla
</div>
<div class="informasjon1" id="Contact" style="display:none;"><br>
blabla
</div>
<div class="informasjon1" id="Project" style="display:none;">
Different bla bla bla
</div>
Im using filtered divs and I want to change the flex-direction of each section only when that specific section is toggled, then go back to original styles when going back to "Show all"
Here is the link for the filtered divs
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements
The W3 Schools code is not very good. It can be improved greatly but the use of data attributes, proper event listeners and event bubbling
All we need to to to get your "flex switch" happening is add/remove a class to the ".container" to indicate if filtered or not
var container = document.querySelector(".container");
//Add an event listener to the div containing the buttons
document.getElementById("myBtnContainer").addEventListener("click", function(event) {
//remove active class from previous active button
this.querySelector(".active").classList.remove("active");
//add active class to clicked item
event.target.classList.add("active");
//Add filitered to ".container" if "All" clicked, remove otherwise
container.classList.toggle("filtered", event.target.dataset.target !== "all")
//Display chosen elements
var elements = container.querySelectorAll(".filterDiv");
for (var i = 0; i < elements.length; i++) {
//Long version of below
//var categoryArray = elements[i].dataset.category.split(",");
//var hasTargetCategory = categoryArray.includes(event.target.dataset.target);
//elements[i].classList.toggle("show",hasTargetCategory);
elements[i].classList.toggle("show", elements[i].dataset.category.split(",").includes(event.target.dataset.target));
}
})
.filterDiv {
background-color: #2196F3;
color: #ffffff;
width: 100px;
line-height: 100px;
text-align: center;
margin: 2px;
flex: none;
}
.container {
margin-top: 20px;
display: flex;
flex-wrap: wrap;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
/*Class to change flex direction*/
.filtered {
flex-direction: column;
}
/*Hide elements without the show class*/
.filtered>.filterDiv:not(.show) {
display: none;
}
<div id="myBtnContainer">
<button class="btn active" data-target="all"> Show all</button>
<button class="btn" data-target="cars"> Cars</button>
<button class="btn" data-target="animals"> Animals</button>
<button class="btn" data-target="fruits"> Fruits</button>
<button class="btn" data-target="colors"> Colors</button>
</div>
<div class="container">
<div class="filterDiv" data-category="cars">BMW</div>
<div class="filterDiv" data-category="colors,fruits">Orange</div>
<div class="filterDiv" data-category="cars">Volvo</div>
<div class="filterDiv" data-category="colors">Red</div>
<div class="filterDiv" data-category="cars,animals">Mustang</div>
<div class="filterDiv" data-category="colors">Blue</div>
<div class="filterDiv" data-category="animals">Cat</div>
<div class="filterDiv" data-category="animals">Dog</div>
<div class="filterDiv" data-category="fruits">Melon</div>
<div class="filterDiv" data-category="fruits,animals">Kiwi</div>
<div class="filterDiv" data-category="fruits">Banana</div>
<div class="filterDiv" data-category="fruits">Lemon</div>
<div class="filterDiv" data-category="animals">Cow</div>
</div>
I didn't understand what you meant by "flexible steering", would it be to replace the phrase "Show all" with the active section? This can be done with jquery, but you would have to replace the element that houses the text.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="all">Show all</button>
<button type="button" id="cars">cars</button>
<script>
$("#cars").on("click", function(){
$("#all").text('Cars');
});
$("#all").on("click", function(){
$("#all").text('Show All');
});
</script>
Alternative without jquery
<button id="all">Show All</button>
<button id="cars" onclick="cars()">Cars</button>
<script>
function cars() {
document.getElementById("all").innerHTML = "Cars";
}
</script>
Alternative to build the tab without so much javascript and css
Bootstrap Collapse: You can use Bootstrap Colapse which already has a structure ready and you would only have to organize the HTML with the divs as per the documentation: https://getbootstrap.com/docs/4.0/components/collapse/
Javascript behavior: Like the previous one, this is a tabbed browsing API, which is identical to the code you are using, with the difference that here you would be using the Bootstrap structure and will not require many modifications, you should note the similarity between this and the previous one, in fact what changes is only the usability, the situations in which you will use one or the other, but the purpose is the same, both seek to hide elements.
https://getbootstrap.com/docs/4.0/components/navs/#javascript-behavior
I have a simple search input that filters divs as you type so that only those divs with matching data attributes are shown.
This works great, but it only returns exact matches. For example, in the snippet below, I can search for "apple" but "apple california" doesn't show the proper div (even though the data attribute contains both of those values). I think this is because it's only searching for an exact match.
How might I adjust this code to search for multiple values in a "data-" element? Ideally I'd like to have it ignore common words like "and," "in," "near," so that a search for:
Apple in California or iphone near california
would still show the Apple div.
Appreciate any advice, I'm stumped! Here's the snippet:
$('[data-search]').on('keyup', function() {
var searchVal = $(this).val();
var filterItems = $('[data-filter-item]');
if (searchVal != '') {
filterItems.addClass('hidden');
$('[data-filter-item][data-filter-name*="' + searchVal.toLowerCase() + '"]').removeClass('hidden');
} else {
filterItems.removeClass('hidden');
}
});
* {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, sans-serif;
}
.hidden {
display: none;
}
input {
background: #cdcdcd;
border: none;
padding: 14px 20px;
}
.items {
margin-top: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="search">
<input type="text" placeholder="search" data-search />
</div>
<div class="items">
<div data-filter-item data-filter-name="apple+iphone+california">Apple</div>
<div data-filter-item data-filter-name="google+nexus">Google</div>
<div data-filter-item data-filter-name="microsoft">Microsoft</div>
</div>
</div>
You can just grab all items and use string.indexOf on each item's data to check the presence of a string in a string.
$('[data-filter-item][data-filter-name]').each(function(element){
var isPresent = $(this).data('filter-name').indexOf(searchVal.toLowerCase()) > -1;
if(isPresent){
// do something
} else {
// do something else
}
});
I am trying to show and hide certain divs within my document.
I have put together code using getElementById and want to apply style.display to each element of array. I am not sure if this is possible.
Currently my code looks like this:
Javascript
<script>
function chart1() {
var show = new array ["#chartdiv1", "#unit-price"];
document.getElementByid("graph-container").show.style.display = "inline";
var hide = new array ["#chartdiv2", "#unit-price-value",
"#chartdiv3", "#unit-price-value"];
document.getElementByid("graph-container").hide.style.display = "none";
};
</script>
HTML
<div id="graph-container">
<!-- Unit Price Dollar -->
<div id="unit-price" style="text-align: center; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size: 14px; color: #666; clear: both; margin-bottom: 20px;">VPM Global Select Opportunities Fund - Dollar Unit Price
<br>Weekly: 2012/02/03 to 2014/10/24</div>
<div id="chartdiv1" style="width:100%; height:600px;"></div>
<!-- Unit Price Dollar Target Return -->
<div id="unit-price-value" style="text-align: center; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size: 14px; color: #666; clear: both; margin-bottom: 20px;">Value of $1000 Invested at inception relative to Target Return
<br>Weekly: 2012/02/03 to 2014/10/24</div>
<div id="chartdiv2" style="width:100%; height:600px;"></div>
<!-- Unit Price Rand Versus Inflation -->
<div id="unit-price-rand" style="text-align: center; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size: 14px; color: #666; clear: both; margin-bottom: 20px;">Value of R1000 Invested at inception relative to Inflation Benchmarks
<br>Weekly: 2012/02/03 to 2014/10/24</div>
<div id="chartdiv3" style="width:100%; height:600px;"></div>
<div style="text-align: center; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size: 12px; color: #666; clear: both; margin-top: 20px;">
<br>* VPM GSO - VPM Global Select Opportunities Fund</div>
<br>
</div>
<!-- End Graph Container-->
Original Javascript that works in IE11, Safari, Opera, FireFox and Chrome
This is the orignal code I created it worked in all the browsers except IE8-10, maybe someone can guide me on this.
function chart1() {
document.getElementById("chartdiv1").style.display = "inline";
document.getElementById("unit-price").style.display = "block";
document.getElementById("chartdiv2").style.display = "none";
document.getElementById("unit-price-value").style.display = "none";
document.getElementById("chartdiv3").style.display = "none";
document.getElementById("unit-price-rand").style.display = "none";
};
</script>
You help is greatly appreciated.
I think that what you are trying to do is this:
function chart1() {
var show = ["chartdiv1", "unit-price"];
for ( var i = 0; i < show.length; ++i )
document.getElementById(show[i]).style.display = "inline";
var hide = ["chartdiv2", "unit-price-value","chartdiv3", "unit-price-value"];
for ( var i = 0; i < hide.length; ++i )
document.getElementById(hide[i]).style.display = "none";
};
In this way you itearate over the two arrays so that the elements in show are shown and the others are hidden.
The problems were:
the IDs if you use plain js and not css or jQuery are without the #
The correct syntax for array is Array
You have to iterate over the elements in order to hide/show each of them
You have to remove the hide/show after the getElementById selection, because in that way you are accessing to a property inside that Object
You are mixing pure JS and JQuery.
hide() and show() in JQUery
So, for you: $("#graph-container").hide();
style.display = "none"; in pure JS
So, for you: document.getElementByid("graph-container").style.display = "none";
For the difference between hidden and none: What is the difference between visibility:hidden and display:none?
Try using this, it should work.
document.getElementById("graph-container").style.visibility="visible"; //Show the container
var hide = new array ["#chartdiv2", "#unit-price-value","#chartdiv3", "#unit-price-value"];
document.getElementById("graph-container").style.visibility="hidden"; //Hide the container
Try this, using javascript
document.getElementById("<your tag id>").style.visibility = "hidden";
And again to show the element, you can use,
document.getElementById("<your tag id>").style.visibility = "visible";
A small demontration i submitted in Snippet. Check if it helps you.
<html>
<body>
<div id="myP">This is a p element.</div>
<button type="button" onclick="myFunction()">Hide content of div</button>
<button type="button" onclick="myFunction1()">Show content of div</button>
<script>
function myFunction() {
document.getElementById("myP").style.visibility = "hidden";
}
function myFunction1() {
document.getElementById("myP").style.visibility = "visible";
}
</script>
</body>
</html>
Using Jquery, you can use show() and hide() method.
JQuery show and hide method