Change HTML element and restore - javascript

I have a website with 2 links.
Once a user clicks a link, this has to become a h2 title without a link.
When the user clicks on the second link, the first links must be restored to its previous state and the second link should become a h2 element.
The links have the purpose of showing a new tab, so they do not reload the page.
HTML (don't mind the href link)
<div id="Panel" class="header-panels">
<a data-linked="#panelImages" href=".../images/#" tabindex="0" class="active">Foto's</a>
<a data-linked="#panelVideos" href=".../videos/#" tabindex="0">Video's</a>
</div>
Is there anyway to do this with javascript/jquery?
I have tried stuff like:
var p = $('.header-panels .active');
var a = $('<h2></h2>').append(p.contents());
p.replaceWith(a);
And it works to change the a tag into h2, but I cannot seem to recreate the a tag with all the attributes when a users clicks a second time.
Or does anyone know a better approach on this?
Thanks in advance?

Fiddle Demo
var all_a = $('#Panel a'); //cache your selector
var h2 = $('<h2/>').attr('id', 'temp');//created a h2 tag with id temp (just for identification if u need to style it)
all_a.click(function (e) {
e.preventDefault();//stop default behavior of click if u want
all_a.show(); //show all a tag inside id Panel
var $this = $(this); //cache selectore
h2.text($this.text()).insertBefore($this); //insert h2 before current a tag clicked and with it's text
$this.hide(); //hide clicked a
});
.insertBefore()

This script let you toggle 'h2' and 'a' without adding third element, it just replace 'h2' with a 'a' element, and add all the parameters of 'a' element to the 'h2' element on the form of data.
$(document).on('click', '#Panel a', function (e) {
e.preventDefault();
$this = $(this);
var $h2Elem = $this.parents('#Panel').find('h2');
console.log($h2Elem);
$h2Elem.each(function (index, item) {
var linked = $(item).data('linked'),
href = $(item).data('href'),
tabindex = $(item).data('tabindex'),
text = $(item).text();
$(item).replaceWith('<a data-liked="' + linked + '" href="' + href + '" tabindex="' + tabindex + '">' + text + '<a>');
});
var linked = $(this).data('linked'),
href = $(this).attr('href'),
tabindex = $(this).attr('tabindex'),
text = $(this).text();
$this.replaceWith('<h2 data-liked="' + linked + '" data-href="' + href + '" data-tabindex="' + tabindex + '">' + text + '<h2>');
});
Fiddle HERE

why don't you use separate elements and hide/show them as required? E.g.
<div id="Panel" class="header-panels">
<a data-linked="#panelImages" href=".../images/#" tabindex="0" class="active" id="fotolink">Foto's</a><h2 id="foto" style="display: none;">Foto's</h2>
<a data-linked="#panelVideos" href=".../videos/#" tabindex="0" id="videolink">Video's</a><h2 id="video" style="display: none;">Video's</h2>
</div>
<script type="text/javascript">
$("#fotolink").on("click", function (e) {
$("#fotolink").hide();
$("#foto").show();
$("#videolink").show();
$("#video").hide();
//e.preventDefault();
});
$("#videolink").on("click", function (e) {
$("#fotolink").show();
$("#foto").hide();
$("#videolink").hide();
$("#video").show();
//e.preventDefault();
});
</script>
EDIT:
In light of your comment, I would then store the reference to the old anchor element and use detach(). E.g.
var oldLink;
function removeH2() {
var h2 = $("#textheading");
if(h2) {
$(oldLink).insertBefore(h2);
$(h2).remove();
}
}
function toText(a) {
oldLink = a;
var h2 = $('<h2 id="textheading">' + $(a).text() + '</h2>');
$(h2).insertAfter(a);
$(a).detach();
}
$("#fotolink").on("click", function (e) {
//e.preventDefault();
removeH2();
toText(e.target);
});
$("#videolink").on("click", function (e) {
//e.preventDefault();
removeH2();
toText(e.target);
});

Related

jQuery $.load Not Executing

I am currently using jQuery on my Django site to reload a div once a user clicks a button.
$(document).ready(function(){
var post_list = Array.from(document.getElementsByClassName("post_container"))
for(var post in post_list){
post_list[post].id = 'post' + post;
}
var $arrows = $(".arrow");
$arrows.each(function(index){
var data = $(this).data();
var element = $(this);
element.on('click', function(event){
if(user_auth){
var currentParentElement = element.parent().parent().parent().get(0);
var id = $(currentParentElement).attr('id');
$(id).load(document.URL + ' ' + id);
}
})
})
});
From the console I can see that currentParentElement and id are pointing to the correct div to reload, but $(id).load() does not seem to be doing anything.
In the image linked below, the clicking the arrow buttons should make the green or red number change. The number does not change when the arrow is clicked, but it does change when I reload the entire page.
https://i.stack.imgur.com/T26wn.png
Your ID selector is missing the # symbol. For example, suppose the id of this target element is "myID":
var id = $(currentParentElement).attr('id');
Then the jQuery selector you're using is:
$('myID')
Which is looking for a <myID> element. There isn't one, so no matches are found, so there's nothing to call .load() on.
You could add the symbol to your selector:
$('#' + id).load(document.URL + ' #' + id);
(Note: The same correction was also made in the selector passed to load() for the same reason.)

Click on div create dynamically

I create some div dynamically and then i would click on one of them and show an alert. But it doesn't go. The div are into another big div that cointain them; if i click on the big div it's ok, but if i change the click event it doesn't go.
Big div:
<div id="combination"> </div>
With this function i create dynamically div (combinationCardID cointains ID of image that i want show in this div):
function showCombinationCard() {
var i, j;
for (i=0; i<combinationCardID.length; i++) {
$("#combination").append("<div id='c" + i + "' class='combcard'> </div>");
for (j=0; j<combinationCardID[i].length; j++) {
var image = $("#" + combinationCardID[i][j]).children("img").clone();
$("#c" + i).append(image);
$("#c" + i).append(" ");
}
}
And this is the click event (if i change .combcard with #combination it's ok, but this not):
$(".combcard").click(function() {
divID = $(this).attr("id");
alert("ok" + divID);
})
Use event delegation
$("#combination").on('click', '.combcard', function() {
divID = $(this).attr("id");
alert("ok" + divID);
})

jQuery show delete display attr

I'm using jQuery hide and show function but I have a problem with the show one.
My javascript code is:
function toggle_visibility(idContent, idLien, question) {
var c = document.getElementById(idContent);
var l = document.getElementById(idLien);
var q = question;
if(c.style.display == 'block') {
$("#" + idContent).hide("blind") ;
l.innerHTML = '<h4><i class=\"icone-rouge icon-right-open-big\"></i>'+ q +'</h4>' ;
}
else {
$("#" + idContent).show("blind") ;
l.innerHTML = '<h4><i class=\"icone-rouge icon-down-open-big\"></i>'+ q +'</h4>' ;
}
}
The problem is that it doesn't work for the hide part when the div is hidden at the load of the page (with display='none'). I can display the block but then I cannot hide it.
I noticed that when I show a content, jQuery delete the display attr in my html style... Maybe there is a link.
Here a link for example : http://jsfiddle.net/29c4D/2/
Thank you.
DescampsAu, since you are using jQuery I rewrote your code to take full advantage of the powerful library. You can see the example in this fiddle.
Let jQuery do the heavy lifting of checking whether an element is hidden or not by making use of either the .toggle() or .slideToggle() methods.
Remove all of the onClick() code within your spans and use this jQuery instead:
jQuery
$(document).ready( function() {
//After the page has loaded, let jQuery know where all of the spans are.
var toggleThis = $(".toggleMe");
//Whenever you click one of the spans do this function.
toggleThis.click( function() {
//Register the span you clicked and the next div that holds the hidden stuffs.
var el = $(this),
nextDiv = el.next(".toggleMeDiv");
//Check if the span's partner div is hidden or showing by checking its css "display" value.
if(nextDiv.css("display") == "block") {
//Change the text of the span to be its title attribute plus whether its partner is showing or hidden.
el.html(el.attr("title")+" hidden");
} else {
el.text(el.attr("title")+" shown");
}
//Let jQuery toggle the partner's visibility.
nextDiv.slideToggle();
});
});
HTML
<span class="toggleMe" title="Quest 1">Quest 1</span>
<div class="toggleMeDiv">Boubou1</div>
<span class="toggleMe" title="Quest 2">Quest 2</span>
<div class="toggleMeDiv">Boubou2</div>
Making this too hard on yourself.
HTML
<span class="toggle" id="lien1" data-original-text="Quest 1">Quest 1</span>
<div id="content1">Boubou1</div>
<span class="toggle" id="lien2" data-original-text="Quest 1">Quest 2</span>
<div id="content2">Boubou2</div>
JS
$(document).ready( function () {
$('.toggle').on('click', function() {
$(this).next('div').toggle('blind', textToggle); // or slideToggle();
});
function textToggle() {
var $target = $(this).prev('span'); // "this" is the div that was toggled.
var originalText = $target.attr('data-original-text');
if ( $(this).is(':visible') ) {
$target.text( originalText + ' open' );
} else {
$target.text( originalText + ' closed' );
}
}
});
A fiddle: http://jsfiddle.net/29c4D/7/
EDIT to include label + effect.

Click based upon value of hash on url

I'm new to working with JS/jQuery, I've been currently trying to figure out how to make this work, by trying many different ways that I've found here and on different sites, and am unable to get this working.
I have a website that has tabs, that changes a div's content when the click on the buttons in the menu. This all works fine, but I want to be able to link to each separate "page" using hash tags example.com/#tab-1
HTML:
<div class="tabWrapper">
<div class="tabContent">
<div class="label">TAB 1</div>
<?php include 'tab1.php'; ?>
</div>
<div class="tabContent">
<div class="label">TAB 2</div>
<?php include 'tab2.php'; ?>
</div>
tabWrapper looks like this after being generated
<div class="tabWrapper">
<ul class="tabs">
<li class="tab-1">TAB 1</li>
<li class="tab-2">TAB 2</li>
</ul>
JS :
// Generate tab navigation
if ($('div.tabWrapper').length != 0)
{
$('div.tabWrapper').each(function()
{
// Prepare tab output
var printTabs = '<ul class="tabs">';
var tabContent = $(this).find('.tabContent');
var tabCount = tabContent.length;
$(tabContent).each(function(key)
{
// Hide tab if it is not the first
if (key != 0)
{
$(this).hide();
}
// Get label for tab
var label = $(this).find('.label').text();
// Use a number if no label was given
if (!label)
{
label = 'Tab ' + (key + 1);
}
// Add id to tab content
$(this).addClass('tab-' + key);
printTabs+= '<li class="tab-' + key + '">' + label + '</li>';
});
// Add tabs
$(this).prepend(printTabs + '</ul>');
$(this).find('li:first').addClass('active');
});
}
// Handle click on tabs
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
{
// Deny click on active element
if ($(this).is('.active'))
{
return false;
}
// Get tab id
var id = $(this).attr('class').split('-');
id = id[1];
// Display and animate new tab content
var parent = $(this).parent().parent();
parent.find('ul.tabs li').removeClass('active');
$(this).addClass('active');
parent.find('.tabContent').hide()
parent.find('.tab-' + id).animate({ opacity: 'show' }, animationSpeed);
});
Here is what I was trying to add, which I don't think is correct
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
which I added in the js file just above
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
I'm not sure how far I'm off with that code, as it doesn't seem to work at all. I just want it to see if there is a hash tag in the url, and if there is then run the click function to change the content.
I hope I explained what I was looking for clear enough. I'd very much appreciate any help with this.
Thank you.
UPDATE:
I updated the code with setInterval as per chiliNUT's suggestion, however it still doesn't appear to be working.
setInterval(hash,1000);
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
UPDATE 2:
Still unable to get this working, anyone able to help?
Thanks.
My tip is using anchor tags as well.
Link
That will open example.com#tab1
The control on page load:
$( document ).ready(function() {
if(window.location.hash == "#tab1"){
$("#someId").click();
}
});
Why not just use anchor tags?
Button to open tab 1

write dynamic html with jquery

Given this fiddle, what is preventing the HTML from being rendered?
JavaScript
$(document).ready(function(){
function loadDiv( divId ) {
$('#' + divId).html('<table><tr><td class="editable" id="' + divId + '">Edit Me</td></tr></table>');
}
$('td.editable').click(function() {
var cellId = $('td.editable').attr('id');
alert(cellId);
});
loadDiv( div1 );
loadDiv( div2 );
});
My intention is to change the clicked cell into an input field and later post from it, but I'm not sure why it's not rendering.
You need to add quotes around your div ids.
loadDiv( "div1" );
loadDiv( "div2" );
http://jsfiddle.net/pp6nv/1/
Since the tables are added after the page loads, you'll have to use .on().
$('body').on("click", "td.editable", function() {
var cellId = $(this).prop('id');
alert(cellId);
});
http://jsfiddle.net/pp6nv/3/

Categories

Resources