I have a <table> which is dynamically created so the width is unknown. I'm trying to add horizontal scroll bars to the top and bottom of it. My current code...
<div class="wrapper1">
<div class="div1" width="<script type=\"text/javascript\">document.write(mytext);</script>">
</div>
</div>
<div class="wrapper2">
<div class="div2">
<table id="table_width">
*table content goes here*
</table>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".wrapper1").scroll(function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
var mytext = document.getElementById("table_width").offsetWidth; //Method 1
var mytext = document.getElementById("table_width").style.width = width + 'px'; //Method 2
</script>
In the last few lines, I've tried two different methods to set the width of the containing <div> to be mytext.
Any ideas why either method isn't working? BTW, I'm not trying both methods at the same time the way it's shown here.
To find the width of an element you need to use window.getComputedStyle followed by getPropertyValue on that returned value. What you are doing now only gives you the CSS value which is not set.
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
The problem could be this.
The script you have written to find mytext is being executed after the table is created. But by the time the div is created value of mytext is not known. So I would recommend doing this.
<!DOCTYPE html>
<div class="wrapper1">
<div id="div1">
</div>
</div>
<div class="wrapper2">
<div class="div2">
<table>
*table content goes here*
</table>
</div>
<script type="text/javascript">
$(function(){
$(".wrapper1").scroll(function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
var mytext = document.getElementById("table_width").offsetWidth; //Method 1
var mytext = document.getElementById("table_width").style.width ; //Method 2
document.getElementById('div1').width = mytext;
</script>
</html>
The above code changes the width of the div after finding the value of mytext.
I ended up using parts of both of the suggested answers for this question. After a lot of fiddling, I ended up with this for the final Javascript...
var elem = document.getElementById("table_width");
var mytext = window.getComputedStyle(elem,null).getPropertyValue("width");
$('#div1').css({'width':mytext});
$('#div1').css({'overflow': 'scroll'});
Related
let say i have this div
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)
I tried using:
$("#button").on("click",function(){
var ReturnedText = $(this).parent(".lookAtMe").text();
console.log(RetrunedText);
});
But the console log would retruned (empty string).
Where did i do wrong? please help. Thankyou very much.
Because there is n o parent with that class. You need find().
Actually you need to write
var ReturnedText = $(this).parent().find(".lookAtMe").text();
$("#button").on("click",function(){
var ReturnedText = $(this).parent().find(".lookAtMe").text();
console.log(ReturnedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I'm writing a HTML code where there are 3 divs - and in the mainDiv2, there is this another div that is hidden. When I click on the mainDiv2, I want to unhide the hiddenDiv(this I'm able to do it). As well as I want this hiddenDiv to be shown in mainDiv1 as a child.
Here is my code.
<div class="mainDiv1">
This si a main div content
</div>
<div class="mainDiv2" onclick="showhiddenDiv()">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
JS
function showhiddenDiv(){
document.getElementById('hiddenDiv').style.display="block";
}
please let me know how can I do this.
Here is a working fiddle. https://jsfiddle.net/8pj3uvfn/1/
Thanks
You can use appendChild like below
function showhiddenDiv() {
var hiddenDiv = document.getElementById('hiddenDiv');
var mainDiv1 = document.getElementsByClassName('mainDiv1')[0];
hiddenDiv.style.display = "block"
mainDiv1.appendChild(hiddenDiv)
}
<div class="mainDiv1" id="mainDiv1">
This is a main div content
</div>
<div class="mainDiv2" onclick="showhiddenDiv()">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
As well as I want this hiddenDiv to be shown in mainDiv1 as a child.
You need to clone the hiddenDiv and put it in mainDiv1.
So modify your method as
function showhiddenDiv(){
var hiddenNode = document.getElementById('hiddenDiv');
hiddenNode.style.display="block";
var copyHiddenNode = hiddenNode.cloneNode( true );
copyHiddenNode.id += "_1"; //change the id so that ids are not duplicated
document.getElementById("mainDiv1").appendChild( copyHiddenNode );
}
You could use appendChild
function showhiddenDiv(){
var hiddenDiv = document.getElementById('hiddenDiv');
document.getElementsByClassName('mainDiv1')[0].appendChild(hiddenDiv);
hiddenDiv.style.display="block";
}
Demo
Assuming that you have set the id attributes of the divs properly,
function showhiddenDiv(){
var hiddenDiv = document.getElementById('hiddenDiv'); //Get the reference
document.getElementById('mainDiv1').appendChild(hiddenDiv) //Chenge the DOM order (you don't have to clone)
hiddenDiv.style.display="block"; //Unhide
}
<div class="mainDiv1">
This si a main div content
</div>
<div class="mainDiv2" onclick="document.getElementById('hiddenDiv').style.display = 'block'">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
I'm new with javascript and I have a tiny problem.
I want to create a function and by pressing that button to invert the two divs ( the first one to be placed second and viceversa). I hope you understand.
I have this code:
<div> text 1 </div>
<div> text 2 </div>
<button> invert </button>
Using pure javascript, you can simply switch the contents of each div:
function flip(){
div1_content = document.getElementById("div1").innerHTML;
div2_content = document.getElementById("div2").innerHTML;
document.getElementById("div1").innerHTML = div2_content;
document.getElementById("div2").innerHTML = div1_content;
}
<div id="div1"> Text 1 </div>
<div id="div2"> Text 2 </div>
<button onclick="flip()"> Flip it! </button>
We're simply storying the contents of each div, then assigning them to one another. Hopefully, you can take this, learn from it, and apply it how you intend to.
Here is a simple javascript solution
jsFiddle https://jsfiddle.net/xzLme043/2/
myFunction = function(){
var div1 = document.getElementById('one');
var div2 = document.getElementById('two');
var html = div1.innerHTML;
div1.innerHTML = div2.innerHTML;
div2.innerHTML = html;
};
For this solution, you'll just place the current two divs in another parent div container, and then just insert the second div before the first, on the click of the invert button. No changing or pulling of inner text or HTML required.
function invertDivs(parentDiv) {
var first = document.getElementById(parentDiv).firstElementChild;
console.log(first);
var second = document.getElementById(parentDiv).lastElementChild;
console.log(second);
document.getElementById(parentDiv).insertBefore(second, first);
}
<div id="parent">
<div id="first">div 1</div>
<div id="second">div 2</div>
</div>
<button onclick="invertDivs('parent');">invert</button>
I need to get the text in a sibling span element and the name of a parent div when the user clicks on an "a" element that will be repeated hundreds of times. (In the example below I just include two but you get the idea.) See my code below and please help me understand how to name them at the spot marked with comments. Both javascript and jQuery are available to solve the problem.
<html>
<head>
<script language="javascript" type="text/javascript" src="/wp-includes/js/jquery/jquery.js"></script>
</head>
<body>
<div id="div001">
<span class="book">Book 1</span> <span class="month">January</span>
</div>
<div id="output001"></div>
<div id="div002">
<span class="book">Book 2</span> <span class="month">February</span>
</div>
<div id="output002"></div>
<script id="source" language="javascript" type="text/javascript">
var $j = jQuery.noConflict();
$j( ".citation" ).click(function ( )
{
event.preventDefault();
var book = ???; // <==== How do I capture “Book 1” or “Book 2”?
var divName = ???; // <==== How do I capture “div001” or “div002”?
$j('#' + divName.replace('div', 'output')).html(book);
});
</script>
</body>
</html>
This question might have dozens of answers, but here is just one of them:
$j(document).on("click", ".citation", function ( ){
var book = $(this).find('span.book').html();
var divName = $(this).parent().attr('id');
}
Note that since your elements are created dynamically you should use .on().
var book = $(">span.book", this).html();
var divName = $(this).closest("div").prop('id');
Here's a jsbin: http://jsbin.com/civizugene/1/edit?html,css,console,output
You can use jQuery find() to find elements by class or type.
I have some text inside <span></span> tags and I want to change that text to something else when page is loaded.
So lets say default text is 'Story' (outputted by some CMS system and I can't edit it). So when page is loaded, .js detects that 'Story' word and replaces it with 'View This Story'.
Is that possible somehow?
Cheers
Update: I did search before asking and none of those methods I found works. Like I said the text is outputted by CMS and it gives wrong title, the title itself cannot be edited via CMS because it is used for other terms and tagging which is correct, so I was looking for js workaround to rename it on page load.
And span has no ID and I cannot give it any ID, because like I said it works as designed by CMS.
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
As you can see spans do not have IDs, but repeating classes only.
UPDATED as per OP request
You can replace any text within spans. You could even use regular expressions to make it more flexible, but let's leave this for now:
Native Javascript
var lookupSpanAndReplace = function(textFrom, textTo) {
var spans = document.getElementsByTagName('span');
for (i=0; i<spans.length; i++)
if (spans[i].innerHTML.indexOf(textFrom) >= 0)
spans[i].innerHTML = mySpan.innerHTML.replace(textFrom, textTo);
}
lookupSpanAndReplace("Story", "My New Text");
jQuery
var lookupSpanAndReplace = function(textFrom, textTo) {
$('span:contains(' + textFrom + ')').each(function(index, element) {
$(element).text($(element).text().replace(textFrom, textTo));
});
}
lookupSpanAndReplace("Story", "My New Text");
Try
$('#spanID').text("View This Story");
or if you want to replace a part of text
$('#spanID').text(function () {
return this.innerHTML.replace('Story', 'View This Story');
});
Give you span an ID and then run text([your new text]) on that node:
HTML
<span id="mySpan">Story</span>
jQuery
$('#mySpan').text("View This Story");
JSFiddle with jQuery
Or you can do it without jQuery:
document.getElementById("mySpan").innerHTML = "View This Story";
JSFiddle with plain 'ol Javascript
<script>
function changeSpan(){
var spans = document.getElementsByTagName ("span");
for (i = 0; i < spams.length; i++){
spans[i].innerHTML = textThatYouWant ();
}
}
</script>
<head onload="changeSpan()" >
<tile> ... </title>
</head>
<body>
...
</body>
Use the following to solve the issue.
HTML code:
<html>
<head>
<script>
function replace_text_span()
{
for(i=0;i<document.getElementsByTagName('span').length;i++)
{
document.getElementsByTagName('span')[i].innerHTML=document.getElementsByTagName('span')[i].innerHTML.replace("Story","View This Story");
}
}
</script>
<style>
</style>
</head>
<body onload="replace_text_span()">
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
</body>
</html>