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
Related
I am using mvc .net core for a project and I have a view page. I need some id values from this page for using them inside partial view. Because I am using those id values for foreign key in another table to post. From main page these values posts in database correctly. I always post 5 values and always 5 id there in database I saw when I checked. But when I click the accordion this id always turns first id from these 5 values. if I posted as 6,7,8,9,10 it just turns me 6 and it doesn't matter if I clicked the last one in the page or first one. But context and title always correct when I check it from database and from page.
I tried a few jquery code but they didn't work correctly. I need the correct id values when I click other accordions.
I would be glad for any kind of help. Thanks a lot.
Here is my code:
#model IEnumerable<match>
#{
ViewData["Title"] = "Home Page";
}
<head>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<style>
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
}
</style>
</head>
<body>
<h4>Title List:</h4>
<table class="table table-hover">
#foreach (var item in Model)
{
<tr class="yzt">
<td class="xyz" id="item_title" >
<button class="accordion" id="title" >#Html.DisplayFor(modelItem => item.title)</button>
<div class="panel">
<p id="modelId" hidden>#Html.DisplayFor(modelItem=>item.Id)</p>
<p>#Html.DisplayFor(modelItem => item.context)</p>
#await Html.PartialAsync("Create", item.Exams#*, Exams*#)
</div>
</td>
</tr>
}
</table>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
//document.querySelectorAll('.accordion').forEach(link => this.addEventListener('click', myFunction))
//function myFunction() {
// document.getElementById("matchId").value = document.getElementById("modelId").innerHTML;
// console.log("value is" + document.getElementById("matchId").value);
//}
document.querySelectorAll('.panel').forEach(link => this.addEventListener('click', myFunction))
function myFunction() {
document.getElementById("matchId").value = document.getElementById("modelId").innerHTML;
console.log("value is" + document.getElementById("matchId").value);
}
//document.querySelectorAll(".accordion")
//document.getElementById("match_title").value = document.getElementById("title").innerHTML;
</script>
</body>
I recommend you to write like this:
<div class="panel" id=#item.Id onclick="test(#item.Id)">
function test(val){
alert(val);
}
Your code will create multiple having id "title" and multiple having id "modelId", and this is also the reason why you always get the id from the first item, what you write document.getElementById("modelId").innerHTML will always get the first dom element which id = "modelId"
I have a button and it should increase the font size when clicked and if it's clicked again it should decrease the font. Also the value of the button should change to Increase Font / Decrease Font. So, basically I want to make the button toggle from increasing the font to 16px then decreasing to 14px if clicked again.
EDIT: I made it work but it doesn't keep repeating. Only works twice and that's it
HTML
<p id="increase">Lorem Ipsum.</p>
<input onclick="font()" style="background-color:#72cf26" type="submit" value="Increase Font" id = "fontbutton"/>
JS
function font(){
var fontsize = document.getElementById('increase');
var fontbutton = document.getElementById('fontbutton');
if (fontbutton.value == "Increase Font"){
fontsize.classList.add("font16");
document.getElementById('fontbutton').value = "Decrease Font";
}else if (fontbutton.value == "Decrease Font"){
fontsize.classList.add("font14");
document.getElementById('fontbutton').value = "Increase Font";
}
}
CS
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
You should use fontbutton.value instead of fontbutton.getElementById.value and remove the previous class using fontsize.classList.remove to add the new one using fontsize.classList.add:
function font(){
var fontsize = document.getElementById('increase');
var fontbutton = document.getElementById('fontbutton');
if (fontbutton.value == "Increase Font"){
fontsize.classList.remove("font14");
fontsize.classList.add("font16");
fontbutton.value = "Decrease Font";
}else if (fontbutton.value == "Decrease Font"){
fontsize.classList.remove("font16");
fontsize.classList.add("font14");
fontbutton.value = "Increase Font";
}
}
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
<p id="increase" class="font14">Lorem Ipsum.</p>
<input onclick="font()" style="background-color:#72cf26" type="submit" value="Increase Font" id = "fontbutton"/>
The above requirement can be implemented using
element.classlist.add and element.classlist.remove functions.
Here is a copy of the working code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.font16{
font-size:16px;
background-color:#72cf26;
}
.font14{
font-size: 14px;
background-color:#72cf26;
}
</style>
</head>
<body>
<p id="increase">Lorem Ipsum.</p>
<button id="fontbutton" class="font14" onclick="toggleFont()">
Increase Font
</button>
<script>
function toggleFont() {
var element = document.getElementById("fontbutton")
var buttonText = element.innerHTML
element.classList.remove("font14")
element.classList.remove("font16")
if(buttonText.indexOf("Increase") >= 0) {
element.classList.add("font16")
element.innerHTML = "Decrease font"
} else {
element.classList.add("font14")
element.innerHTML = "Increase font"
}
}
</script>
</body>
</html>
Output:
More information:
https://www.w3schools.com/howto/howto_js_toggle_class.asp
$(document).ready(function(){
var flag = true;
$('.btn').click(function(){
$(this).find('span').toggleClass('hidden');
if(flag) {
$('#increase').addClass('font16');
$('#increase').removeClass('font14');
flag = !flag;
}else {
$('#increase').removeClass('font16');
$('#increase').addClass('font14');
flag = !flag;
}
});
});
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
.hidden {
display: none;
}
p{ font-size: 10px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="increase">Lorem Ipsum.</p>
<button class="btn">
<span>Increse Font</span>
<span class="hidden">Decrese Font</span>
</button>
Your approach is complicated, JS directly offers a toggle method to add / delete a class and which returns a boolean value.
The only difficulty is that you should not forget to add !important to upgrade the size.
const paragraphInc = document.getElementById('increase')
, buttonSize = document.getElementById('fontbutton')
;
buttonSize.onclick = () =>
{
buttonSize.textContent = (paragraphInc.classList.toggle('Size16'))
? 'Decrease Font'
: 'Increase Font'
}
#fontbutton {
background-color:#72cf26;
padding: 7px 12px;
}
#increase {
font-size: 14px;
}
.Size16 {
font-size: 16px !important;
}
<p id="increase">Lorem Ipsum.</p>
<button id="fontbutton">Increase Font</button>
How to add event delegation to dynamically created divs, to change property of the target div? I've tried several suggestions that I found for event delegation but none of them work. I think I'm making some mistakes but I don't know how to fix.
I am trying to develop a file thumbnail list interface with HTML and JavaScript. I made a method that draws thumbnails dynamically from an Array. And now I want to add some functions to manipulate the thumbnails, ex. changing border color of the item(div) when it is clicked.
First I tried loop-method to add event listeners to the divs, but it didn't work well. And now I learned that event delegation is better way to add event listeners to dynamically created elements. But the problem is that though I'v tried codes but they didn't work at all.
I think I am making some mistakes or mis-using methods but I don't know what is the problem.
JavaScript
function drawThumbnails(area, list){
var j
var createdList = []
for (j=0; j<list.length; j++){
var thmb = document.getElementById("fileThumb");
var name = document.getElementById("itemName");
var date = document.getElementById("itemDate");
var thmbimg = document.getElementById("fileThumbImage");
var thmbicon = document.getElementById("file_icon_thumb");
name.innerHTML=list[j][0];
date.innerHTML=list[j][1];
if (list[j][2] == "folder"){
thmbimg.src = "thmb_folder.png";
thmbicon.style.display = "none";
}
else {
if (list[j][2] == "img"){
thmbimg.src=getthmbimgsample();
}
else{
thmbimg.src = getThmbimg(list[j][2]);
}
thmbicon.style.display = "block";
thmbicon.src = getThmbicon(list[j][2]);
}
var cln = thmb.cloneNode(true);
cln.style.display = "block";
document.getElementById(area).append(cln);
createdList.push(cln);
}
thmbLists.push(createdList);
}
drawThumbnails("folderArea", folders);
drawThumbnails("fileArea", files);
document.getElementById("folderArea").addEventListener('click',function(e){
if(e.target && e.target.className == "fileThumb"){
e.target.style.borderColor = "#408CFF";
}
});
HTML
<body>
<div class = "contentArea" id="contentArea">
<div class = "thumbArea" id="folderArea">
<div class = "fileThumb" id="fileThumb">
<img src="icon_thumb_folder.png" class="fileThumb_normal" id="fileThumbImage">
<div class="fileName">
<img src="icon_thumb_file.png" style="width: 20px;" id="file_icon_thumb">
<div class="fileNameLine" id = "itemName">File/FolderName</div>
<div class="fileNameDate" id="itemDate">Date</div>
</div>
</div>
</div>
<div class = "contentAreaSectionHeader">
<input type="checkbox" id="chTest2" name="chTest2">
<label for="chTest2"><span>Files</span></label>
</div>
<div class = "thumbArea" id="fileArea">
</div>
</body>
CSS
.fileThumb{
width: 213px;
height: 183px;
border-radius: 2px;
border-style: solid;
border-width: 1px;
border-color: #EEEEEE;
text-align: center;
position: relative;
float:left;
margin: 18px;
display: none;
overflow: hidden;
}
My problem is i want to make this post in one line and scroling on the x and the y hidden
My html
<div id='related-post'>
<div class='relhead'>
<h5><span>أنميات أخرى</span></h5>
<div class='clear'/>
<b:loop values='data:post.labels' var='label'
<script expr:src='"/feeds/posts/default/-/" + data:label.name +
"?
alt=json-in-script&callback=relpostimgcuplik&"'
type='text/javascript'/>
</b:loop>
<ul id='related-summary'>
<script type='text/javascript'>relatedscript();</script>
</ul>
</div>
</div>
My css`
#related-post { display : inline-block; font-family: 'jsbold'; font-size:
14px; padding-bottom: 7px; border-bottom: 4px solid $(main.color); line-
height: 18px; font-weight: 700; color: #111; text-transform: uppercase;}
My java script
<script type='text/javascript'>
//<![CDATA[
//Related Post
var relnojudul = 0;
var relmaxtampil = 8;
var numchars = 90;
var reljudul=new Array();var relurls=new Array();var relcuplikan=new Array();var relgambar=new Array();function saringtags(g,h){var e=g.split("<");for(var f=0;f<e.length;f++){if(e[f].indexOf(">")!=-1){e[f]=e[f].substring(e[f].indexOf(">")+1,e[f].length)}}e=e.join("");e=e.substring(0,h-1);return e}function relpostimgcuplik(h){for(var e=0;e<h.feed.entry.length;e++){var g=h.feed.entry[e];reljudul[relnojudul]=g.title.$t;postcontent="";if("content" in g){postcontent=g.content.$t}else{if("summary" in g){postcontent=g.summary.$t}}relcuplikan[relnojudul]=saringtags(postcontent,numchars);if("media$thumbnail" in g){postimg=g.media$thumbnail.url}else{postimg="http://1.bp.blogspot.com/-htG7vy9vIAA/Tp0KrMUdoWI/AAAAAAAABAU/e7XkFtErqsU/s1600/grey.GIF"}relgambar[relnojudul]=postimg;for(var f=0;f<g.link.length;f++){if(g.link[f].rel=="alternate"){relurls[relnojudul]=g.link[f].href;break}}relnojudul++}}function contains(a,e){for(var f=0;f<a.length;f++){if(a[f]==e){return true}}return false}function relatedscript(){var v=new Array(0);var w=new Array(0);var x=new Array(0);var A=new Array(0);for(var u=0;u<relurls.length;u++){if(!contains(v,relurls[u])){v.length+=1;v[v.length-1]=relurls[u];w.length+=1;w[w.length-1]=reljudul[u];x.length+=1;x[x.length-1]=relcuplikan[u];A.length+=1;A[A.length-1]=relgambar[u]}}reljudul=w;relurls=v;relcuplikan=x;relgambar=A;for(var u=0;u<reljudul.length;u++){var B=Math.floor((reljudul.length-1)*Math.random());var i=reljudul[u];var s=relurls[u];var y=relcuplikan[u];var C=relgambar[u];reljudul[u]=reljudul[B];relurls[u]=relurls[B];relcuplikan[u]=relcuplikan[B];relgambar[u]=relgambar[B];reljudul[B]=i;relurls[B]=s;relcuplikan[B]=y;relgambar[B]=C}var r=0;var D=Math.floor((reljudul.length-1)*Math.random());var z=D;var q;var t=document.URL;while(r<relmaxtampil){if(relurls[D]!=t){q="<li class='news-title clearfix'>";q+="<a href='"+relurls[D]+"' rel='nofollow' target='_top' title='"+reljudul[D]+"'><div class='overlayb'></div><img src='"+relgambar[D]+"' /></a>";q+="<a class='relinkjdulx' href='"+relurls[D]+"' target='_top'>"+reljudul[D]+"</a>";q+="<span class='news-text'>"+relcuplikan[D]+"</span>";q+="</li>";document.write(q);r++;if(r==relmaxtampil){break}}if(D<reljudul.length-1){D++}else{D=0}if(D==z){break}}};
//]]>
</script>
I'm kind of confused on what you're asking. This can probably be done with just CSS. Can you use inspect element and copy the code it produces when the page is loaded or paste a link to your page where the script is being used so I could take a look.
From what I think you're asking you could try doing something like this
<div class="container">
<div class="container-inner">
<div class="item"></div><div class="item"></div><div class="item"></div>
</div>
</div>
CSS:
.container {width:100%}
.container-inner {width:200%}
.item{float:left}
Just make sure your inner container is wider than your outer container and that should give you the scrolling effect you're looking for. Hope this helps
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
}
});