I am trying to make this audio player work from wayback machine with absolutely no luck after almost three hours messing with it.
Here's the Javascript for the audio player I think.
mejs.mepIndex = 0, mejs.players = {}, mejs.MediaElementPlayer = function(b, c) {
return this instanceof mejs.MediaElementPlayer ? (this.$media = this.$node = a(b), this.node = this.media = this.$media[0], "undefined" != typeof this.node.player ? this.node
.player : (this.node.player = this, "undefined" == typeof c && (c = this.$node.data("mejsoptions")), this.options = a.extend({}, mejs.MepDefaults, c), this.id =
"mep_" + mejs.mepIndex++, mejs.players[this.id] = this, this.init(), this)) : new mejs.MediaElementPlayer(b, c)
}, mejs.MediaElementPlayer.prototype = {
hasFocus: !1,
controlsAreVisible: !0,
init: function() {
var b = this,
c = mejs.MediaFeatures,
d = a.extend(!0, {}, b.options, {
success: function(a, c) {
b.meReady(a, c)
},
error: function(a) {
b.handleError(a)
}
}),
e = b.media.tagName.toLowerCase();
b.isDynamic = "audio" !== e && "video" !== e, b.isVideo = b.isDynamic ? b.options.isVideo : "audio" !== e && b.options.isVideo, c.isiPad && b.options.iPadUseNativeControls ||
c.isiPhone && b.options.iPhoneUseNativeControls ? (b.$media.attr("controls", "controls"), c.isiPad && null !== b.media.getAttribute("autoplay") && b.play()) :
c.isAndroid && b.options.AndroidUseNativeControls || (b.$media.removeAttr("controls"), b.container = a('<div id="' + b.id + '" class="mejs-container ' + (mejs.MediaFeatures
.svg ? "svg" : "no-svg") +
'"><div class="mejs-inner"><div class="mejs-mediaelement"></div><div class="mejs-layers"></div><div class="mejs-controls"></div><div class="mejs-clear"></div></div></div>'
).addClass(b.$media[0].className).insertBefore(b.$media), b.container.addClass((c.isAndroid ? "mejs-android " : "") + (c.isiOS ? "mejs-ios " : "") + (c.isiPad ?
"mejs-ipad " : "") + (c.isiPhone ? "mejs-iphone " : "") + (b.isVideo ? "mejs-video " : "mejs-audio ")), c.isiOS ? (c = b.$media.clone(), b.container.find(
".mejs-mediaelement").append(c), b.$media.remove(), b.$node = b.$media = c, b.node = b.media = c[0]) : b.container.find(".mejs-mediaelement").append(b.$media),
b.controls = b.container.find(".mejs-controls"), b.layers = b.container.find(".mejs-layers"), c = b.isVideo ? "video" : "audio", e = c.substring(0, 1).toUpperCase() +
c.substring(1), b.width = b.options[c + "Width"] > 0 || b.options[c + "Width"].toString().indexOf("%") > -1 ? b.options[c + "Width"] : "" !== b.media.style
.width && null !== b.media.style.width ? b.media.style.width : null !== b.media.getAttribute("width") ? b.$media.attr("width") : b.options["default" + e +
"Width"], b.height = b.options[c + "Height"] > 0 || b.options[c + "Height"].toString().indexOf("%") > -1 ? b.options[c + "Height"] : "" !== b.media.style
.height && null !== b.media.style.height ? b.media.style.height : null !== b.$media[0].getAttribute("height") ? b.$media.attr("height") : b.options[
"default" + e + "Height"], b.setPlayerSize(b.width, b.height), d.pluginWidth = b.width, d.pluginHeight = b.height), mejs.MediaElement(b.$media[0], d),
"undefined" != typeof b.container && b.controlsAreVisible && b.container.trigger("controlsshown")
},
Here's the HTML Code for the audio player, I've tried literally every single combination with javascript that I can think of to get this working.
<section class="section with-player">
<header>
<h1>Now Playing: <span id="playerInfo">SONG NAME</span></h1>
</header><span data-next="javascript: void()" data-prev="javascript: void()" id="links"></span>
<div id="fromAlbum">
<div class="mejs-container svg mejs-audio" id="mep_0" style="width: 100%; height: 50px;">
<div class="mejs-inner">
<div class="mejs-mediaelement">
<audio id="mejs" preload="none" src=""></audio>
</div>
<div class="mejs-layers">
<div class="mejs-poster mejs-layer" style="display: none; width: 100%; height: 50px;"></div>
</div>
<div class="mejs-controls">
<div class="mejs-time-rail" style="width: 2px;">
<span class="mejs-time-total" style="width: 1px;"><span class="mejs-time-buffering" style="display: none;"></span><span class=
"mejs-time-loaded"></span><span class="mejs-time-current"></span><span class="mejs-time-handle"></span><span class="mejs-time-float"><span class=
"mejs-time-float-current">00:00</span><span class="mejs-time-float-corner"></span></span></span>
</div>
<div class="mejs-button mejs-prevtrack hide-for-small">
<a class="" href="javascript:%20void()"><i class="glyphicon glyphicon-backward"></i></a>
</div>
<div class="mejs-button mejs-playpause-button mejs-play">
<button aria-controls="mep_0" aria-label="Play/Pause" class="btn btn-link" title="Play/Pause" type="button"><i class=
"glyphicon glyphicon-play"></i></button>
</div>
<div class="mejs-button mejs-nexttrack hide-for-small">
<a class="" href="javascript:%20void()"><i class="glyphicon glyphicon-forward"></i></a>
</div>
<div class="mejs-button mejs-volume-button mejs-mute">
<button aria-controls="mep_0" aria-label="Mute Toggle" title="Mute Toggle" type="button"></button>
</div>
<div class="mejs-horizontal-volume-slider mejs-mute">
<div class="mejs-horizontal-volume-total"></div>
<div class="mejs-horizontal-volume-current" style="width: 29px;"></div>
<div class="mejs-horizontal-volume-handle" style="left: 23px;"></div>
</div>
<div class="mejs-time">
<span class="mejs-currenttime">00:00</span> <span>/</span> <span class="mejs-duration">00:00</span>
</div>
</div>
<div class="mejs-clear"></div>
</div>
</div>
</div>
<div class="mejs-list">
<ol>
<li>
<span>TTG (feat. Kevin Gates)</span> <a class="btn btn-dark btn-xs" href=
"https://web.archive.org/web/20161017173851/http://www.albumkings.com/albums/71500-woptober-by-gucci-mane/intro-fuck-12"><i class=
"glyphicon glyphicon-download-alt"></i> download</a> <a class="btn btn-dark btn-xs tracklist-play" data-file="http://filecandy.net/mp3embed-t7yjo5m8jey6.mp3" href=
"<?php the_permalink(); ?>#"><i class="glyphicon glyphicon-play"></i> play</a>
</li>
<li>
<span>I Am Who They Say I Am (feat. Kevin Gates and Quando Rondo)</span> <a class="btn btn-dark btn-xs" href=
"https://web.archive.org/web/20161017173851/http://www.albumkings.com/albums/71500-woptober-by-gucci-mane/aggressive"><i class=
"glyphicon glyphicon-download-alt"></i> download</a> <a class="btn btn-dark btn-xs tracklist-play" data-file="http://filecandy.net/mp3embed-v8sfz29sx5du.mp3" href=
"<?php the_permalink(); ?>#"><i class="glyphicon glyphicon-play"></i> play</a>
</ol>
</div>
</section>
Link to the Wayback Machine.
I've added working file links to the above loop, but I can't get the top portion to display the current playing song from just copying the code from wayback. The file which contains the javascript is all.min.js
Related
The below is part of a media player. Unfortunately, I cannot find the reason why the event listener is not registering the clicks on the hearts (when a user favorites a song). I have tried several implementations and I am researching for the last week with no success. Can you help?
How can I make the click listener to update the heart count?
HTML
<div class="player">
<div class="dashboard">
<header>
<p>Playing:</p>
</header>
<div class="cd">
<div class="cd-thumb">
</div>
</div>
<div class="control">
<div class="btn btn-random inactive">
<i class="fas fa-random"></i>
</div>
<div class="btn btn-prev">
<i class="fas fa-step-backward"></i>
</div>
<div class="btn btn-toggle-play">
<i class="fas fa-pause icon-pause"></i>
<i class="fas fa-play icon-play"></i>
</div>
<div class="btn btn-next">
<i class="fas fa-step-forward"></i>
</div>
<div class="btn btn-mute-unmute inactive">
<i class="fas fa-volume-up"></i>
</div>
</div>
</div>
<div class="playlist">
</div>
Script 1
render: function () {
let that = this;
fetch("hearts.txt")
.then(function(response) {
return response.json();
})
.then(function(heartCounts) {
let t = that.songs.map(
(t, e) => `
<div class="song ${
e === that.currentIndex ? "active" : ""
}" data-index="${e}">
<div class="thumb"
style="background-image: url('${t.image}')">
</div>
<div class="body">
<h3 class="title">${t.name}</h3>
<p class="author">${t.singer}</p>
</div>
<div class="heart" data-song-id="${e}">
<i class="fa fa-heart${
heartCounts[e] ? " active" : ""
}"></i> <span>${heartCounts[e] || 0}</span>
</div>
</div>
`
);
playlist.innerHTML = t.join("");
});
},
Script 2
const getHeartCounts = function () {
let xhr = new XMLHttpRequest();
xhr.open("GET", "return.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let heartCounts = JSON.parse(xhr.responseText);
// Update the heart count displays
document.querySelectorAll(".heart i + span").forEach((countDisplay, i) => {
countDisplay.innerHTML = heartCounts[i];
});
// Update the active heart icons
document.querySelectorAll(".heart i").forEach((heart, i) => {
if (heartCounts[i] > 0) {
heart.classList.add("active");
}
});
}
};
xhr.send();
};
document.addEventListener("DOMContentLoaded", function () {
// Add click listener to update the heart count
document.querySelectorAll(".heart").forEach(function (heart) {
heart.addEventListener("click", function (e) {
let target = e.target,
songIndex = parseInt(target.dataset.songId),
countEl = target.querySelector("span"),
heartCount = countEl ? parseInt(countEl.innerHTML) : 0,
isActive = target.classList.contains("active");
// Update the heart count
heartCount = isActive ? heartCount - 1 : heartCount + 1;
if (countEl) {
countEl.innerHTML = heartCount;
}
let heartIcon = target.querySelector("i");
if (heartIcon) {
heartIcon.classList.toggle("active", !isActive);
}
// Update the heart count on the server
let xhr = new XMLHttpRequest();
xhr.open("POST", "store.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("index=" + songIndex + "&count=" + heartCount);
});
});
// Update the heart counts on page load
getHeartCounts();
});
I'm doing an e-trade site with jQuery; however, when I increase then submit one of the products, they all get the properties of the first product. I defined the products as a json to a variable.
How can I create dynamic cards with jquery?
Here is how it looks:
İmage
Here is the source code:
$(document).on('click', '.number-spinner button', function() {
var btn = $(this),
oldValue = btn.closest('.number-spinner').find('input').val().trim(),
newVal = 0;
newVal = (btn.attr('data-dir') === 'up') ? parseInt(oldValue) + 1 : (oldValue > 1) ? parseInt(oldValue) - 1 : 0;
btn.closest('.number-spinner').find('input').val(newVal);
});
let html = data.reduce((acc, {name,value,image,counter,totalMoney}) =>
acc + `
<div class='card col-md-3'>
<img class='card-img-top' src="${image}" alt='Card image cap'>
<div class='card-body'>
<h5 class='card-title'>${name}</h5>
<p class="card-text">${value}</p>
<input class="money-input money" value="${value}"/>
<div class="number-spinner">
<div class="input-group number-spinner">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-minus" data-type="minus" data-dir="dwn"><span>-</span></button>
</span>
<input min="1" class="adet input-number" value="${counter}" type="number">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-plus" data-type="plus" data-dir="up"><span>+</span></button>
<div class="total-price"></div>
</span>
</div>
</div>
<button class="submit">Add To Card</button>
</div>
</div>`
, ``);
$('#list').append(html);
const adet = $(".adet").val()
const money = $(".money").val()
const totalMoney = adet * money;
var endText = 'Price'
var space = ' '
$( ".submit" ).click(function() {
$(".total-price").text($(".adet").val() * totalMoney);
$('.total-price').append( space + endText);
});
The "problem" is that you have (possibly) multiple elements with the class .adet and .money. However, the .val() method of a jQuery collection only extracts the value of the first element it contains. See the jQuery docs:
Get the current value of the first element in the set of matched elements...
jQuery docs
I am trying to write some code that updates a header tag and a button tag. However, when I use the method .text(); it does not work. So I looked up the proper way to do it via other stack overflow questions, and I see basically the same thing. Everyone is telling me to use .text() or .html(). So I am really confused on why it is not working. I am not sure if it has anything to do with values already in the tag.
HTML:
<div class="contents">
<div class="card text-center myCard">
<div class="card-header"></div>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text"></p>
<button type="button" class="btn btn-primary ttBtn"></button>
</div>
<div class="card-footer text-muted"></div>
</div>
</div>
jQuery:
$(".eBtn").on(
"click",
function(event) {
event.preventDefault();
var href = $(this).attr('href');
console.log(href);
$.get(href, function(ary2, status) {
$("#displayAppName").val(ary2.appname);
$("#appcode").val(ary2.appcode);
$("#editStatus").val(ary2.status);
if (ary2.mapstatus == "" || ary2.mapstatus == null) {
mapBool = true;
$("#mapStatus").val("");
$("#createBtn").val('Create');
$('#modalCreateBtn').attr(
'href',
'/create?currentAppcode='
+ ary2.appcode
+ "¤tAcro="
+ ary2.acronym
+ "¤tAppname="
+ ary2.appname);
console.log("Card Create: " + $(".card-title").val());
} else {
$("#mapStatus").val("Mapped");
$("#createBtn").val('Edit');
$('#modalCreateBtn').attr(
'href',
'/edit?currentAppcode='
+ ary2.appcode
+ "¤tAcro="
+ ary2.acronym);
mapBool = true;
console.log("Card Edit: " + $(".card-title").val());
}
});
console.log("Main Boolean : " + this.mapBool)
console.log("Main Boolean : " + mapBool)
if(mapBool){
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").text("New Mapping after");
}
$("#exampleModal").modal();
});
jQuery Change HTML:
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").text("Continue");
Created variable ary2. Hope this help you.
var ary2 = [];
if (ary2.mapstatus == "" || ary2.mapstatus == null) {
$("#mapStatus").val("");
$("#createBtn").val('Create');
$('#modalCreateBtn').attr(
'href',
'/create?currentAppcode=' +
ary2.code +
"¤tAcro=" +
ary2.acro +
"¤tAppname=" +
ary2.name);
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").html("Continue");
} else {
$("#mapStatus").val("Mapped");
$("#createBtn").val('Edit');
$('#modalCreateBtn').attr(
'href',
'/edit?currentAppcode=' +
ary2.code +
"¤tAcro=" +
ary2.acro);
}
$(document).ready(function() {
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").html("Continue");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contents">
<div class="card text-center myCard">
<div class="card-header"></div>
<div class="card-body">
<h5 class="card-title">Application not mapped!</h5>
<p class="card-text">Click the "New Tier" button to begin mapping.
</p>
<button type="button" class="btn btn-primary ttBtn">New
Mapping</button>
</div>
<div class="card-footer text-muted"></div>
</div>
</div>
This is the code that I'm wiring which returns
var list = hyperHTML.wire(doc)`
<li class=${['chatEl', 'dropInChat', isUnsynced, docType, isChatShown, isUnread, userType].join(' ')} rel=${doc.id}>
<div class=${['chatAvatar', avatarNumCss].join(' ')} style=${avatarCss} >${[multiAvatar]}</div>
<div class='chatTypeIndicator'></div>
<div class='chatListItem'>
<div class='chatLastMessage'>
${wire(doc)`<h4><span class="userName">${name}</span>${handle !== '' ? wire(doc)`<span class="handle">#${handle}</span>` : ''}</h4>`}
${((hasEmojie) ? wire(doc)`<div class="has-emoji">${[emojione.shortnameToImage(content)]}</div>` : wire(doc)`<div class="media-attached-last-msg">${[emojione.unicodeToImage(doc.type === 'txt' ? msgTODisplay : content)]}</div>` )}
</div>
<div class=${['chat-list', 'chat-date-time'].join(' ')} data-livestamp=${posted}> ${outDate} </div>
${wire(doc)`<div class=${notifDiv}></div>`}
<div class='delBtn'>
<a class = 'blockFromChat' href="#"></a>
<a class = 'favFromChat' href="#"></a>
<a class = 'delFromChat' href="#"></a>
</div>
</div>
</li>`
return list;
Inside variables will calculate for desired output
var now = moment();
var posted = moment(doc.date);
var outDate = '';
if(now.date() === posted.date() && now.month() === posted.month() && now.year() === posted.year()){
outDate = posted.format('h:mm A');
}else if(now.date() - 7 <= posted.date() && now.month() === posted.month() && now.year() === posted.year()){
outDate = posted.format('ddd');
}else{
outDate = posted.format('MM/DD/YYYY');
}
The above is where the timestamp outDate is calculated and below is the multiavatar variable which is used in the wire()
multiAvatar.push(wire()<div class=${['groupAvatar', 'g_'+ avatarNum].join(' ')} style=${{backgroundImage: 'url(' + miniAvatarUrl + ')', backgroundSize: 'cover'}}></div>)
and the below code is the where I'm binding the dom.
bind(document.querySelector('#chatListDisplay'))`
${lastMessageList.map(function(doc){
return hyperRenderChatList(doc);
})}`
Here is the output of DOM:
<li class="chatEl dropInChat private isShown " rel="57abce9a0b4a520100a3e591" style="display: block;" __plugindomid="pgm272917962927">
<div class="chatAvatar undefined" style="background-image: url(img/ProfileIcon.svg); background-size: cover;" __plugindomid="pgm1289375326530"></div>
<div class="chatTypeIndicator"></div>
<div class="chatListItem" __plugindomid="pgm655347260182">
<div class="chatLastMessage" __plugindomid="pgm550534885881">
<h4 __plugindomid="pgm1452658781039"><span class="userName" __plugindomid="pgm188048463623">Displace Hashery </span><span class="handle" __plugindomid="pgm1268924787529">#Displace</span></h4>F
</div>
<div class="chat-list chat-date-time needs_to_be_rendered" datetime="2018-03-01T04:39:28.424Z" __plugindomid="pgm41746152612">7 minutes ago</div>
<div class="chat-message-status delivered" __plugindomid="pgm1045616861867"></div>
<div class="delBtn" __plugindomid="pgm1469370042923">
<a class="blockFromChat" href="#" __plugindomid="pgm1287760548168"></a>
<a class="favFromChat" href="#" __plugindomid="pgm648316158041"></a>
<a class="delFromChat" href="#" __plugindomid="pgm775096736090"></a>
</div>
</div>
The __plugindomid attribute is set by google-maps.
I made some really small WYSIWYG text editor, with some very basic functions, and this is the code (See live demo in jsfiddle):
HTML:
<section class="wysiwyg-editor" data-wysiwyg="true">
<h2 id="hdwysiwygfw3v">WYSIWYG : By #natanel97</h2>
<textarea id="wysiwyg_ta_ead"></textarea>
<div class="wysiwyg-editor-toolbar wysiwyg-editor-toolbar-menu">
<!-- enable only for test purposes
<button class="wysiwyg-editor-toolbar-menu menu-button" onclick="wysiwyg_save()"><i class="fa fa-floppy-o"></i></button>
-->
<button class="wysiwyg-editor-toolbar-menu menu-button" onclick="wysiwyg_addtag( 'strong' )"><i class="fa fa-bold"></i></button>
<button class="wysiwyg-editor-toolbar-menu menu-button" onclick="wysiwyg_addtag( 'em' )"><i class="fa fa-italic"></i></button>
<button class="wysiwyg-editor-toolbar-menu menu-button" onclick="wysiwyg_addtag( 'ins' )"><i class="fa fa-underline"></i></button>
<button class="wysiwyg-editor-toolbar-menu menu-button" onclick="wysiwyg_toggle( 'wtgl_link' )"><i class="fa fa-link"></i></button>
<div class="wysiwyg-editor-toolbar-menu hover-button-drop-down">
<button class="wysiwyg-editor-toolbar-menu menu-button">Font Size <i class="fa fa-caret-down"></i></button>
<ul class="wysiwyg-editor-toolbar-menu drop-down-menu">
<li>9pt</li>
<li>11pt</li>
<li>13pt</li>
<li>16pt</li>
<li>19pt</li>
<li>21pt</li>
<li>26pt</li>
</ul>
</div>
<div class="wysiwyg-editor-toolbar-menu hover-button-drop-down">
<button class="wysiwyg-editor-toolbar-menu menu-button">Color <i class="fa fa-caret-down"></i></button>
<ul class="wysiwyg-editor-toolbar-menu drop-down-menu color-selection">
<li>Black</li>
<li>White</li>
<li>Dark red</li>
<li>Orange</li>
<li>Ocean blue</li>
<li>Grass green</li>
<li>Fuchsia pink</li>
<li><i class="fa fa-ellipsis-h"></i></li>
</ul>
</div>
<div class="wysiwyg-editor-toolbar-menu hover-button-drop-down">
<button class="wysiwyg-editor-toolbar-menu menu-button">Font <i class="fa fa-caret-down"></i></button>
<ul class="wysiwyg-editor-toolbar-menu drop-down-menu">
<li>Default</li>
</ul>
</div>
<button class="wysiwyg-editor-toolbar-menu menu-button" onclick="wysiwyg_toggle( 'wtgl_info' )"><i class="fa fa-info"></i></button>
</div>
<div class="wysiwyg-editor-contents" id="wysiwyg_ce_ead" contenteditable="true"></div>
<div class="wysiwyg-scenes">
<div class="scene" id="wtgl_link">
<div class="wysiwyg-scenes-tables">
<div class="tr">
<div class="td" style="width:120px;">Link url:</div>
<div class="td"><input type="text" id="wysiwyg-link-href" placeholder="Must start with "http://"" /></div>
</div>
<div class="tr">
<div class="td">Text:</div>
<div class="td"><input type="text" id="wysiwyg-link-text" placeholder="Describe the link" /></div>
</div>
<div class="tr">
<div class="td"></div>
<div class="td">
<button onclick="wysiwyg_addtag( 'a', 'wysiwyg-link-href', 'wysiwyg-link-text' );wysiwyg_toggle( 'wtgl_link' )">Add link</button>
<button type="reset" onclick="wysiwyg_toggle( 'wtgl_link' )">Cancel</button>
</div>
</div>
</div>
</div>
<div class="scene" id="wtgl_color">
<div class="wysiwyg-scenes-tables">
<div class="tr">
<div class="td">Custom HTML Color:</div>
</div>
<div class="tr">
<div class="td"><input type="text" id="wysiwyg-text-color" maxlength="6"
onkeypress="if( this.value == '#' || this.value==' ' ){ this.value = ''; }" onblur="if( this.value == '#' || this.value==' ' ){ this.value = ''; }"
placeholder="Without the '#'" /></div>
</div>
<div class="tr">
<div class="td">
<button onclick="wysiwyg_addtag( 'span', null, null, null, 'wysiwyg-text-color' );wysiwyg_toggle( 'wtgl_color' )">Add</button>
<button type="reset" onclick="wysiwyg_toggle( 'wtgl_color' )">Cancel</button>
</div>
</div>
</div>
</div>
<div class="scene" id="wtgl_info">
<div class="wysiwyg-scenes-tables">
<div class="tr">
<div class="td">
<p><strong>Untitled WYSIWYG</strong></p>
<p>Text editor</p>
<p>v0.1</p>
<p>
Written & Developed by #natanel97</p>
<p>
<br />
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">
<img alt="Creative Commons license" src="https://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png" />
</a>
<br />
<span style="font-size:11.6px;">This work is licensed under a
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">
Attribution-NonCommercial-ShareAlike 4.0 International </a>.
</span>
<br />
</p>
<button type="reset" onclick="wysiwyg_toggle( 'wtgl_info' )">Close</button>
</div>
</div>
</div>
</div>
</div>
</section>
JavaScript:
function wysiwyg_convert() {
var wysiwyg_textarea = document.querySelector( '.wysiwyg-editor textarea' );
var wysiwyg_div_edit = document.querySelector( '.wysiwyg-editor .wysiwyg-editor-contents' );
wysiwyg_div_edit.onkeypress = function() {
if( wysiwyg_textarea.value != wysiwyg_div_edit.innerHTML ) {
wysiwyg_textarea.value = wysiwyg_div_edit.innerHTML;
}
else {
if( wysiwyg_div_edit.innerHTML != wysiwyg_textarea.value ) {
wysiwyg_div_edit.innerHTML = wysiwyg_textarea.value;
}
}
}
}
function wysiwyg_addtag( tag, href, title, fontsize, color ) {
var tag;
var wysiwyg_div_edit = document.querySelector( '.wysiwyg-editor .wysiwyg-editor-contents' );
if( tag == 'strong' || tag == 'em' || tag == 'ins' ) {
wysiwyg_div_edit.innerHTML = wysiwyg_div_edit.innerHTML + ' <' + tag + '>Text</' + tag + '>';
}
else if( tag == 'img' || tag == 'br' ) {
if( tag == 'img' ) {
wysiwyg_div_edit.innerHTML = wysiwyg_div_edit.innerHTML + ' <' + tag + ' src="' + href + '" alt="' + title + '" />';
}
if( tag == 'br' ) {
wysiwyg_div_edit.innerHTML = wysiwyg_div_edit.innerHTML + ' <' + tag + ' />';
}
}
else {
if( tag == 'a' ) {
var href = document.getElementById( href ).value;
var htxt = document.getElementById( title ).value;
if( href != null ) {
wysiwyg_div_edit.innerHTML = wysiwyg_div_edit.innerHTML + ' <' + tag + ' href="' + href + '">' + htxt + '</' + tag + '>';
}
}
if( tag == 'span' ) {
if( fontsize != null ) {
wysiwyg_div_edit.innerHTML = wysiwyg_div_edit.innerHTML + ' <' + tag + ' style="font-size:' + fontsize + 'pt;">Text</' + tag + '>';
}
else if( color != null ) {
if( document.getElementById('wtgl_color').style.display == 'block' ) {
var color = document.getElementById( color ).value;
}
wysiwyg_div_edit.innerHTML = wysiwyg_div_edit.innerHTML + ' <' + tag + ' style="color:#' + color + ';">Text</' + tag + '>';
}
}
}
}
function wysiwyg_save() {
// enable it only for testing purposes
var wysiwyg_textarea = document.querySelector( '.wysiwyg-editor textarea' );
alert( wysiwyg_textarea.value );
}
function wysiwyg_toggle( id ) {
var id = document.getElementById( id );
if( id.style.display == 'block' ) {
id.style.display = 'none';
}
else {
id.style.display = 'block';
}
}
document.addEventListener( 'DOMContentLoaded', function() {
wysiwyg_convert();
});
I want to create function that will receive selected text, if selected, inside the div, and when one of the styling buttons will be pressed, it will make something like: <someHTMLtag [...]>Selected Text</someHTMLtag>.
Can I make it using the function that I already have - wysiwyg_addtag and just add some code inside? If I can, how?
Javascript has a built in window method called window.getSelection()
You can use this to turn the selected text into a string like so
var text = window.getSelection().toString();
Then it would be as easy as creating a line of code like so:
var replace = "<b>" + text + "</b>"
And injecting that into the HTML. It would be wise to cleanse your input however to prevent some sort of XSS.
Here's some documentation on the method: https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection