I'm struggling to get this working because I don't know the right formatting.
What I am attempting is to get a CSS modal to display depending on what a user selects as a value in a Javascript applet.
The idea is to return .style.display = "block";
function onClick(event){
<something>.style.display = "block";
}
Where contains a value that has being saved in the format of intersects[0].object.title
So if for example I have selected "manhattan"
alert(intersects[0].object.title)
I'll get the string "manhattan" displaying correctly. That works perfectly.
But I can't get manhattan.style.display = "block"; returned and WORKING inside the function? I tried :
function onClick(event){
intersects[0].object.title.style.display = "block";
}
Also tried
function onClick(event){
(intersects[0].object.title).style.display = "block";
}
Any help would be greatly appreciated
This may not be directly what you're looking for, but it may help anyways. To make it work in your case, just change the button press to be a check for the selected value.
Rather than adjusting the CSS directly, this route modifies the element's classList to remove or add a .hidden class that contains the correct CSS.
// Loop through all modal buttons
document.querySelectorAll('.modal-button').forEach(function(element) {
// Add a click event listener to all modal buttons
element.addEventListener('click', function() {
// Toggle the target modal on click
toggleModal(element.dataset.target);
});
});
// Create the function to toggle the modals
function toggleModal(target) {
// Find the target
let targetElement = document.querySelector(target);
// Check if the target is hidden
if (targetElement.classList.contains('hidden')) {
// If it is, show it
targetElement.classList.remove('hidden');
} else {
// If it isn't, hide it
targetElement.classList.add('hidden');
}
}
.hidden {
display: none;
}
<button data-target="#modal" class="modal-button">Toggle Modal</button>
<div id="modal" class="hidden">Hey there, I'm a modal!</div>
I'm not certain from your question how the pieces of your puzzle are related to one another, and it would be helpful if you could clarify by showing more of your HTML and Javascript code, but I'll toss a couple of ideas at you in the meantime. Apologies if I'm telling you stuff you already know.
The only sort of object you would usually be able to set "style.display" on is an HTML element. To tell Javascript which HTML element you want to modify, you usually use a CSS selector like "document.getElementById('myDiv')"
It sounds like "manhattan" might be a piece of information you could use to uniquely identify the HTML element you intend to show. If so, there are four simple parts to showing the correct element:
associate the element with that particular string (eg via an id)
get the string at runtime (the same way as you did for the alert)
select the element based on the matching string
display the selected element
All together, it might look like this:
<div id="manhattan"></div>
<script>
var identifier = intersects[0].object.title;
alert(identifier) //I'm assuming this alerts "manhattan"
var elementToShow = document.getElementById(identifier);
elementToShow.style.display = "block";
</script>
Is this on the right track? If not, just provide more detail, and I'll see what else I can suggest.
Give to you div some id and then just change that:
<div id="test"></div>
document.getElementById("test").style["display"] = "block";
or
document.getElementById("test").style.display = "block";
or
document.getElementById("test").style.setProperty('display', 'block');
or
document.getElementById("test").setAttribute('display', 'block');
Related
I'm having an issue where my textarea value is returning an empty string. I have a modal which opens on a dblclick event where there's a textarea and a button. I want that when the button is clicked the text written in the textarea is fetched and stored in a variable to be used in other functions. By the way when I click on the button the returned text is "".
the textarea html is:
<textarea id="text-comment" placeholder="Insert a new comment" style="min-width:100%"></textarea>
the button html is:
<button class="btn btn-default" data-dismiss="modal" id="edit">Edit</button>`
the function code is:
$(document).on('click', '#edit', function(){ //edits the selected note
var classes = $(selectedNote).attr("class").toString().split(' ');
var id = classes[2];
var newText = $("#text-comment").val();
console.log("new text is: "+newText);
$(selectedNote).attr("title", newText);
for(var i = 0; i < temporaryNotes.length; i++) {
if(temporaryNotes[i]["ref"] == id) {
temporaryNotes[i]["text"] = newText;
}
}
for(var i = 0; i < notes.length; i++) {
if(notes[i]["ref"] == id) {
deleteNotes.push(notes[i]);
notes[i]["text"] = newText;
}
}
})
I'm going to go on a limb here. The limb might break but who knows?
I believe your modal's contents are defined within the HTML itself. Perhaps you have <div class="modal-content"> or something - I don't know what modal plugin you're using (but if I ever write one, it will use <script type="text/html"> specifically to prevent this issue...)
The problem with defining modals in this way is that the "template" contents are themselves part of the document, even if the "base" one is never shown. The modal plug-in can then call cloneNode on the template and render that as the modal. Simple, right?
Not quite. IDs must be unique on the page, so any modal plug-in that uses cloneNode to render will end up with duplicate IDs all over the place.
To find out if this is the case, try running this code when your modal is visible on-screen:
alert($("[id='text-comment']").length);
This will show how many elements have that ID (whereas #text-comment may just stop after the first one). This value should be exactly 1. If it is 2 (or worse, more!) then you do indeed have a badly implemented modal plugin.
Without knowing exactly which plugin you're using nor how it works, I would suggest finding some way to uniquely identify the displayed modal as opposed to the template, and don't use IDs inside the template.
You'll need to use your browser's Developer Tools to do this, but as an example if your modal appears with class="modal-display" then you could do something like this:
var button = $(this),
container = button.closest(".modal-display"),
textarea = container.find("textarea"),
value = textarea.val();
This kind of "relative search" for elements is much more flexible, and it will help you in future to learn this kind of thing. But for now, it should work around the issue of the duplicate IDs.
Background My page creates a list of objects based on rows of an SQL Database. For each object, a DIV is dynamically generated that contains a few items including a LinkButton and a further child DIV that is initially hidden. I want the link button to toggle the child DIV's hidden property. The JavaScript is not dynamically generated and is included in the ASPX page.
Problem I don't know how to make this generated LinkButton fire JavaScript that is included in the ASPX page and pass in the correct DIV's ID.
I'm guessing I need to add an attribute to the button like so:
myButton.Attributes.Add(reference to JS function + parameter of DIV's ID)
Maybe like:
myButton.Attributes.Add("onclick", "Show_Hide_Display('"<%="' +idString+ '".ClientID%>"')");
Where the button is given an attribute of a JS onClick handler pointing to the function "Show_Hide_Display" and a parameter of a DIV's ID that is calculated as the rendered ID. This syntax is incorrect though.
How do I write this so it calls 'Show_Hide_Display' and passes the ID of the current child DIV? All of the DIVs have the same ID apart from a number that references their row number, for example '"myDiv_" + counter.ToString'
The JavaScript I am trying to add a call to on the button:
function Show_Hide_Display(divID) {
var div = document.getElementById(divID);
var style = document.defaultView.getComputedStyle(div);
var display = style.getPropertyValue('display');
if (display == '' || display == 'block') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
Use the following syntax ...
myButton.Attributes.Add("onclick", "Show_Hide_Display(this.id);");
the above syntax allows to call the function with id as its parameter.
suggestion:
Try to write a common function which does not depend on generated ids of controls.
If this is not useful for your requirement, please post your code which might gives me a better idea.
If you are using jQuery, you could you jQuery delegate method.
$(document).on("click", "div.parent", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};
You need to implement getSubDivByParent according your DOM structure.
If you are not using jQuery, you need to attach event yourself. For each dynamically generated element. You need to manually add following script in your server code to register event.
... your html code ...
<script>
var elem = document.getElementById('new-created-element');
elem.addEventListener("click", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};)
</script>
My suggestion is use jquery to achieve the functionality.
My solution works if you want to toggle the immediate div for the link.just call onclientclick method to toggle the div.
in linkbutton onclientclick="Show_Hide_Display(this)"
function Show_Hide_Display(id) {
$(id).next('div').toggle();
}
I hope this helps you .. Thanks
I've added some custom elements to be included with my WooCommerce account page to be seen with the order history. Unfortunately the page is setup with tabs to only display the information pertaining to the active tab.
I'm not very familiar with jquery, but I thought it would be simple enough to use Jquery to hide the divs I added when the order history has a display of none.
I added the following script to my theme's main.js file:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
When the class .my_account_orders has a display of none it should change the div I added (.paging-nav) to have a display of none. But it just doesn't work.
Is there something wrong with this script or do I need to do something special to initiate it? Since it's in my theme's main.js file and I used $(document).ready(function() I figured it would just load with the page.
Any help with this would be greatly appreciated.
Instead of using:
var display = $('.my_account_orders');
Implement it into the if statement like this:
if($('.my_account_orders').css("display") == "none") {
Because originally it is trying to find a variable called $display, so it would return a syntax error of undefined.
You've got an errant $ in your if statement. This should work instead:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
Also keep in mind that your var display is only going to match the first element that has a class of my_account_orders, so if there are multiple elements with that class, and they don't all have the same display, you could get unexpected results.
Try this:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
I believe it's a very lame way to check for a css property such as display to determine if an element is hidden or not. With jquery, you can make use of :hidden selector which determines whether an element is hidden and return a bool value.
$(document).ready(function(){
if($('.my_account_orders').eq(0).is(":hidden")) // eq(0) is optional - it basically targets the 1st occurring element with class 'my_account_orders'
{
$('.paging-nav').css("display","none");
}
});
Example : https://jsfiddle.net/DinoMyte/sgcrupm8/2/
I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.
Does anyone know how to do replace multiple text by clicking a button with jQuery?
I've built a website that displays some text/data eg; "£100.00", but I what I need is to be able to 'replace' those monetary values with "£XXX.XX" with a 'Hide' button like you get on some banking websites. For example one web page has:
£100.00, £200.00, £130.00 etc etc..
...so when a user presses the Hide button, all of the numbers on the page turn to £XXX.XX. Ideally, the button should then display "Show" instead of "Hide" and switch back when toggled.
This is for a static dummy site, so no data base.
I suspect this is best handled with jQuery?
Thanks for your time,
D.
Case 1: Controlled Input
Assuming you can at least wrap all monetary values with something like this:
<span class="money-value">£200.00</span>
<span class="money-value">£300.50</span>
And that you can add button declared with:
<button id="secret-button">hide</button>
Then you could have some jQuery code doing this:
/**
* Simple search and replace version.
*/
$(function() {
$("#secret-button").click(function() {
$(".money-value").html($(".money-value").html().replace(/[0-9]/g,"X"));
});
});
or a more advanced one with:
/**
* Complet version.
*
* 1) on button click, if asking to hide:
* 1.1) iterate over all entries, save their text, and replace it with markers
* 1.2) toggle the button's text to "show"
* 2) on button click, if asking to show:
* 2.1) iterate over all entries, restore previous text
* 2.2) clear the hidden store
* 2.3) toggle the button's text to "hide"
*/
$(function() {
var hiddenStore = [];
$("#secret-button").click(function() {
if ($(this).html() == "hide") {
$(".money-value").each(function () {
var text = $(this).html();
hiddenStore.push(text);
$(this).html(text.replace(/[0-9]/g,"X"));
});
$(this).html("show");
} else {
$(".money-value").each(function (i) {
var text = hiddenStore[i];
$(this).html(text);
});
hiddenStore = [];
$(this).html("hide");
}
});
});
Complete solution is here: See here: http://jsfiddle.net/u79FV/
Notes:
this won't work for input field values
this assumes your text entries have been marked as shown above
Does what you want with the button's changing state.
Saves the values and puts them back.
Meant to work even if new fields are added dynamically.
Shankar Sangoli's answer uses a different way of saving the stored data, which you could as well consider (using the jQuery .data() method).
you may want to switch the button to an <input type="button" /> tag, in which case you'd use .val() instead of .html() to toggle its text.
Case 2: Uncontrolled Input
Assuming you don't have control over where the values may show up, then you need to do something a bit more complicated, which is to look in the whole page for something that would look like a currency format. I'd advise against it.
But, the jQuery Highlight plugin could be something to look at, as its code does something similar (in that it searches for pieces of code to modify), and you could then reuse some of solution 1 to make it fit your purpose.
That would be harder to design in a fool-proof fashion though.
You could use a regular expression:
var expression = /\d{1}/g;
var newString = myString.replace(expression,"X");
Then just dump newString into whatever control you need it to appear in.
Edit:
A jQuery idea for something like this would be to give all of the controls that have these numbers a common class identifier to make them easy to grab with the selector:
$(".numbers").each(function() {
$(this).text($(this).text().replace(/\d{1}/g, "X"));
}
... more readable ...
$(".numbers").each(function() {
var text = $(this).text();
var newText = text.replace(/\d{1}/g, "X");
$(this).text(newText);
}
If your markup is something like this you can try this.
<span>£1000.00</span><span class="showhide">Hide</span>
JS
$('.showhide').click(function(){
var $this = $(this);
var $prev = $this.prev();
if(!$prev.data('originalvalue')){
$prev.data('originalvalue', $prev.text());
}
if($this.text() == 'Hide'){
$this.prev().text($prev.data('originalvalue').replace(/\d{1}/g,"X"));
$this.text('Show');
}
else{
$prev.text($prev.data('originalvalue'));
$this.text('Hide');
}
});
In the above code I am basically storing the original value using jQuery data method within the span element itself which is used to display the actual value.
Once you click on Hide, get the previous span using prev() method and set its text with original value replacing all the numbers in it by X. Then change the link text from Hide to Show.
Next when you click on Show get the previous span using prev() method and set its text with the original value and change the link text from Show to Hide.
References: .prev(), .data()
$('#yourButton').click(function(){
var saveText = $('body').text();
$(this).data('oldText', saveText);
if ($(this).text() == "Hide"){
$('body').text($('body').text().replace(/\d{1}/, "X"));
$(this).text('Show');
}
else{
$('body').text($(this).data('oldText'));
$(this).text('Hide');
}
});
This is kind of a complicated problem actually. You will need to be able to save the state of the text when its in number form so you will be able to toggle back and forth. The above code is untested but hopefully it will give you an idea what you need to do.
function toggleMoney() {
$('.money').each(function() {
var $$ = $(this), t = $$.text();
$$.text($$.data('t') || t.replace(/\d/g, 'X')).data('t', t);
});
$('#toggleButton').text($('.money').text().match(/\d/) ? 'hide' : 'show');
}
http://jsfiddle.net/DF88B/2/