I have a JQuery function that handles hiding and showing of a multiple divs on href push.
jQuery(function() {
//hide element
jQuery(".targetDiv").css("display", "none");
// Hook the button click
jQuery(".showEpisodes").click(function(e) {
// To prevent reloading of page
e.preventDefault();
//toggle and hide all other div tags
jQuery('#'+$(this).attr('target')).toggle('fast', function(){
jQuery('.targetDiv').not($(this)).hide();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="style1">
<span class="image">
<img src="">
</span>
<a href="#/" class="showEpisodes" target="1">
<h2>Label</h2>
<div class="content"></div>
</a>
</article>
<div id="1" class="targetDiv">
<ul>
<li><button><span>1</span></button></li>
<li><button><span>GitHub</span></button></li>
<li><button><span>Phone</span></button></li>
<li><button><span>Email</span></button></li>
<li><button><span>StackOverflow</span></button></li>
<li><button><span>StackOverflow</span></button></li>
</ul>
</div>
This works fine, it's when i try to generate the articles with javascript using json to populate information in the tags that i run into trouble. Just to simplify it, i call a function:
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
function createArticleRow() {
var sectionDiv = document.getElementById('videoElements');
var art = document.createElement("article");
art.setAttribute('class', 'style1');
sectionDiv.appendChild(art);
//for images
var span = document.createElement("span");
span.setAttribute('class', 'image');
var image = document.createElement("img");
image.setAttribute('src', 'coverUrl');
art.appendChild(span);
span.appendChild(image);
var href = document.createElement("a");
setAttributes(href, {"href": "#/", "class": "showEpisodes", "target": "1"});
art.appendChild(href);
var h2Tag = document.createElement("h2");
h2Tag.innerHTML = 'title';
href.appendChild(h2Tag);
var divcont = document.createElement("div");
divcont.setAttribute("class", "content");
href.appendChild(divcont);
var h3Tag = document.createElement("h3");
h3Tag.innerHTML = 'description';
divcont.appendChild(h3Tag);
}
function createDivRow(){
var sectionDiv = document.getElementById('videoElements');
var infoDiv = document.createElement("div");
setAttributes(infoDiv, {"id": 1, "class": "targetDiv"});
// infoDiv.setAttribute("class", "hide");
var trailerVideo = document.createElement("iframe");
setAttributes(trailerVideo, {"width":420, "height": 315, "src": "embededTrailerLink"});
infoDiv.appendChild(trailerVideo);
sectionDiv.appendChild(infoDiv);
}
createArticleRow();
createDivRow();
jQuery(function() {
//hide element
jQuery(".targetDiv").css("display", "none");
// Hook the button click
jQuery(".showEpisodes").click(function(e) {
// To prevent reloading of page
e.preventDefault();
//toggle and hide all other div tags
jQuery('#'+$(this).attr('target')).toggle('fast', function(){
jQuery('.targetDiv').not($(this)).hide();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="videoElements" class="tiles"></section>
For some reason this is working fine. But when I run this, the hrefs manually inputted work fine, but the generated html opens a new link with the same html page.
I feel like my problems have something to do with the href tag "#/" but i've tried many variations. I also thought that the might be some ordering issue with my import scripts.
I have opened up the elements console in a browser and the two are identical structurally, and both can access jquery.
Has anyone had similar experiences with this?
Related
Before I get in to this, I know I should learn jQuery but I haven't got to that yet, I want to learn raw JavaScript first! Well, mostly. Can someone help me without the use of jQuery please just for understanding, thank you!:
Hi, I'm new to JavaScript, not long started learning it as you can see by the first code (which works so I'm leaving it) for the navigation.
However, my problem comes on the 2nd piece of code I'm trying something from a different angle after watching videos on event listeners etc and everything I have written makes sense, to me, I'm going through it step by step, it's selecting all the right stuff, but it's still not showing the desired result!!
When you click CSS i want it to show the div with id "cs", and same for the HTML and JavaScript ones.
I really don't know JavaScript enough to solve this myself, I can not think of anything AT ALL to help with the problem!
Somebody save me, please, my mind is going crazy and I want to go to bed!
Here is the code, and here is the JS fiddle: https://jsfiddle.net/pmj26o9p/2/
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
switcheroo.onclick = function() {
if (switcheroo.style.display === "none") {
switcheroo.style.display = "";
} else {
switcheroo.style.display = "none";
}
}
EDIT: On reading through the code again I don't think it will achieve what I want even if it works. This will let me show and hide whichever I'm clicking right?
I want to show the clicked one but then hide / apply display:none to all others that aren't clicked.
My example below will show the chosen block and hide the others, as per your EDIT comment.
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
function contentShow(el) {
var whichOne = el.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
// show selected block, hide the others
switch (switcheroo) {
case htm:
htm.style.display = "block";
css.style.display = "none";
js.style.display = "none";
break;
case js:
htm.style.display = "none";
css.style.display = "none";
js.style.display = "block";
break;
case css:
htm.style.display = "none";
css.style.display = "block";
js.style.display = "none";
break;
}
}
<span data-id="htm" onClick="contentShow(this)" style="margin-right:10px;color:red; cursor:pointer">Click to show the HTML Block</span>
<span data-id="css" onClick="contentShow(this)" style="margin-right:10px;color:green; cursor:pointer">Click to show the CSS Block</span>
<span data-id="js" onClick="contentShow(this)" style="margin-right:10px;color:blue; cursor:pointer">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>
you are binding a second event handler to the switcheroo element, but the click event is not triggered so nothing happens.
If you want to make a toggle function on the switcheroo variable, you should do this instead:
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
return toggleDisplay(switcheroo);
}
function toggleDisplay(elem) {
if (elem.style.display === "none") {
elem.style.display = "";
} else {
elem.style.display = "none";
}
}
Ignoring your other bad practices, change
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
switcheroo.onclick = function() {
if (switcheroo.style.display === "none") {
switcheroo.style.display = "";
} else {
switcheroo.style.display = "none";
}
}
to something more like:
var doc = document;
function E(id){
return doc.getElementById(id); // you guessed it - same as document.getElementById, without typing it every time
}
var htm = E('htm'), css = E('css'), js = E('js');
contentShow = (function(){ // self-executing scopes off var showing - variable style assignment requires function definition before execution
var showing = false;
return function(){ // returns unexecuted function
var ht = E('ht').style, cs = E('cs').style, jsc = E('jsc').style;
if(showing){
ht.display = cs.display = jsc.display = 'none'; showing = false;
}
else{
ht.display = cs.display = jsc.display = 'block'; showing = true;
}
}
})();
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);
See updated JSFiddle here.
If there are no other click Events on those Elements, you could even change
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);
to
htm.onclick = css.onclick = js.onclick = contentShow;
JSFiddle here
but keep in mind this technique overwrites previous Events of the same type.
Here is a variation of #K Scandrett answer which add some scalability/flexibility
var navElements = document.getElementsByClassName("nav");
//Add Event Listeners
for(var i = 0; i < navElements.length; i ++)
{
navElements[i].addEventListener('click', contentShow, false);
}
function contentShow(el) {
var whichOne = el.target.attributes["data-id"].value;
var target = document.getElementById(whichOne);
for(var i = 0; i < navElements.length; i ++)
{
var content = document.getElementById(navElements[i].attributes["data-id"].value)
content.style.display = content === target ? "block" : "none";
}
}
<span data-id="htm" style="margin-right:10px;color:red; cursor:pointer" class="nav">Click to show the HTML Block</span>
<span data-id="css" style="margin-right:10px;color:green; cursor:pointer" class="nav">Click to show the CSS Block</span>
<span data-id="js" style="margin-right:10px;color:blue; cursor:pointer" class="nav">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>
I know you're looking for a javascript solution here.and kudos to you for wanting to understand javascript before getting into jquery, but here is an out of the box solution for you.... pure HTML and CSS
.info {display:none;}
.info:target{display:block;}
Click to show the HTML Block
Click to show the CSS Block
Click to show the JS Block
<br/>
<br/>
<div id="htm" class="info">Some HTML info here</div>
<div id="css" class="info">Some CSS info here</div>
<div id="js" class="info">Some JavaScript info here</div>
What I've done here is, leverage internal page id links and the :target selector. In my mind, this is more semantic and can also still be extended by scripting while still maintaining semantics. This option also gives your uses the option of bookmarking selections etc.
CSS OPTION 2
This option achieves the initial display. It is not as clean and uses absolute positioning and z-indexes. Alos note that is uses a background color to conceal the initial option.
.info {position:relative;}
.info > div {
position:absolute;
top:0;
left:0;
background-color:#FFF;
z-index:10;
display: none;
}
#htm
{
display:block;
z-index:1;
}
.info > div:target {
display: block;
}
Click to show the HTML Block
Click to show the CSS Block
Click to show the JS Block
<br/>
<br/>
<div class="info">
<div id="htm">Some HTML info here</div>
<div id="css">Some CSS info here</div>
<div id="js">Some JavaScript info here</div>
</div>
On a side note you should consider adding/removing css classes using javascript instead of the display property directly. This will enable the use of CSS transitions.
Trying to insert the a certain div once a link is clicked. This link has the div id on its href. So I would like to fetch this data and use it to insert the html into a certain placement in my html DOM.
HTML:
<a class="hotspot article-1-slide-1" href="#product-1">
<span class="hotspot-label pp-icon icon-anime-left-arrow">article 1</span>
</a>
I would like to insert it into this space:
<article class="product-hotspot-display">
<a class="product-hotspot-close pp-icon icon-cross js-product-hotspot-close"></a>
// HERE
</article>
I think that .html() would be the answer. Using this code I get an error. What am I doing wrong?
//product link
$(document).on('click', '.hotspot', function (event) {
event.preventDefault();
var productId = $(this).attr('href');
var productHtml = $(productId).html();
productHtml.insertAfter('.js-product-hotspot-close');
panel.addClass('is-open');
//console.log(productHtml);
});
This should do the trick:
$(document).on('click','.hotspot' , function(event) {
event.preventDefault();
$(this).insertAfter('.js-product-hotspot-close');
});
This worked out for me:
var panel = $('.product-hotspot-display');
var slideWrapper = $('.slide-wrapper');
//product link
$(document).on('click','.hotspot' , function(event) {
event.preventDefault();
var productId = $(this).attr('href');
var productHtml = $(productId).html();
var contentHook = $('.js-product-hotspot-data');
contentHook.empty();
contentHook.html(productHtml);
panel.addClass('is-open');
});
I hope it helps anybody else!
I am trying to show some video files in an Iframe for our company web site. Whenever the user clicks on a video link it will be shown inside an Iframe. I used a Javascript file to perform this action. If I host my videos on you tube, you tube show the title of video.But the javascript I used only change the content of the iframe. I need to show the title of the video files somewhere above the Iframe.
The javascript file I use is this :
<script type="text/javascript">
function ChangeVideoUrl(url)
{
document.getElementById("video_iframe").src = url;
}
</script>
and in I wrote this :
<a class="links" href="JavaScript:ChangeVideoUrl('https://..something.');"> text</a>
Any Ideas?
You can change the actual title of the iframe with iframeReference.contentDocument.title = 'some title'. If you want to change an html title like a h1 tag, you can get the reference to it and set its textContent. See below.
Sample Markup:
<button id="myBtn">Change Iframe</button>
<h1 id="h1Title">Iframe Title</h1>
<iframe id="myIframe"></iframe>
Sample JavaScript:
var myBtn = document.getElementById('myBtn');
var myIframe = document.getElementById('myIframe');
var h1Title = document.getElementById('h1Title');
myBtn.addEventListener('click', changeIframe);
function changeIframe() {
myIframe.contentDocument.title = 'New title!';
h1Title.textContent = 'New Title!';
}
Live demo (click).
As you have now updated your question with your code, there is more to say.
First, inline js (JavaScript inside your html elements) is bad. Read some of these results: https://www.google.com/search?q=Why+is+inline+js+bad%3F
Instead, follow my example and get element references and attach event listeners to them. You can store your data on the element and pull it from there if you want to.
Live demo (click).
Markup:
<div class="links">
<a data-src="a/video" data-title="A video!">Click to Play: A video!</a>
<a data-src="some/title" data-title="Some Title!">Click to Play: Some Title!</a>
<a data-src="another/title" data-title="Another Title!">Click to Play: Another Title!</a>
</div>
<h1 id="h1Title">Iframe Title</h1>
<iframe id="myIframe"></iframe>
JavaScript:
var myIframe = document.getElementById('myIframe');
var h1Title = document.getElementById('h1Title');
var links = document.querySelectorAll('.links a');
for (var i=0; i<links.length; ++i) {
addClickFunc(links[i], i);
}
function addClickFunc(elem, i) {
elem.addEventListener('click', function() {
var title = elem.getAttribute('data-title');
var src = elem.getAttribute('data-src');
changeIframe(title, src);
});
}
function changeIframe(title, src) {
myIframe.src = src;
myIframe.contentDocument.title = title;
h1Title.textContent = title;
}
Assuming some heading for title. You can do this also by javascript.
Give the id for the tag that holding the title of iframe.
Using javascript change the text in that when user click's on video link(chnage innerHTML).
I have a page that has a set of <div> elements, and each one has an anchor tag associated with it. It looks something like this:
<a name="anchor-0"></a>
<div id="div0">Some stuff</div>
<a name="anchor-1"></a>
<div id="div1">More stuff</div>
<a name="anchor-2"></a>
<div id="div2">Yet more stuff</div>
The problem is that this set of <div> and <a> tags are generated by Javascript, and so they don't exist until after the page has been created. When I create a link like this:
http://www.mywebsite.com/mypage.html#anchor-2
... it loads the page but does not jump to the anchor-2 position, which is only created some time after the browser has had time to execute the Javascript that generated it.
How can I get the browser to move to the selected anchor tag position once the Javascript has generated them?
Here is essentially what the Javascript that is generating the HTML looks like:
function init() {
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
gapi.client.load('blogger', 'v2', function() {
var request = gapi.client.blogger.posts.list({
'blogId': 'xxxxxxxxxxxxxxxxxxxxxxxx',
'fields': 'items(content,title)'
});
request.execute(function(response) {
var main = document.getElementById("main");
var anchor = 0;
for (var i = 0; i < response.items.length; i++)
{
var Div = document.createElement("div")
$(Div).append(response.items[i].title);
$(main).append(Div);
anchor = document.createElement("a");
anchor.name = "anchor-" + anchor;
anchor = anchor +1;
}
});
});
}
after creation of element, you could do:
location.hash = "#anchor-2";
or using scrollIntoView
element = document.getElementById('your_element-id');
element.scrollIntoView();
get the hash value from url, by doing something like::
var hashVal = window.location.hash.substr(1);
//then jump to that hash
location.hash = "#" + hashVal;
I have this:
<span class="image"><img src="something.jpg"></span>
I want to transform it to that using javascript:
<span class="image"><img src="something.jpg"></span>
It has to be done using javascript in order to hide the affiliate links.
I have tried this script but it seems not to work:
function changespan() {
find all <span> tags;
for each <span> with class="image"{
URL = "http://domain.com"
Create new link to URL;
insert link into <span>;
}
}
The function is uploaded in file script.js and I load it in this fashion:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
window.onload = changespan;
</script>
EDIT: After this is solved, how could i parse my page to find links in this format:
and then assign this value to variable URL. I need to be able to assign first path to URL_1 second to URL_2 and so on.
This is how you can implement it:
function changespan() {
var spans = document.querySelectorAll('span.image');
for (var i = spans.length; i--; ) {
var a = document.createElement('a');
a.href = "http://domain.com";
spans[i].appendChild(a).appendChild(a.previousSibling);
}
}
http://jsfiddle.net/Tqv76/1/
Here, I translated it to JavaScript keeping your pseudo code as intact as possible
DEMO
window.onload=function() {
var spans = document.getElementsByTagName("span"); // or the newer querySelectorAll
for (var i=0;i<spans.length;i++) {
if (spans[i].className=="image") {
var link = document.createElement("a");
link.href = "http://domain.com";
link.setAttribute("rel","nofollow");
link.className="someclass";
link.innerHTML=spans[i].innerHTML;
spans[i].replaceChild(link,spans[i].getElementsByTagName('img')[0]);
}
}
}